用java程序写出:在E盘根目录下创建文件名为iotest1.txt其内容为outputstream,并将其文件内容拷贝到E盘根目录下,其文件名为iotest2.txt,并显示iotest1.txt的内容。
时间: 2024-03-01 12:50:48 浏览: 81
用java实现的创建文件及写入内容
5星 · 资源好评率100%
好的,这是Java代码实现:
```java
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) {
String filePath1 = "E:/iotest1.txt";
String filePath2 = "E:/iotest2.txt";
String content = "outputstream";
// 在E盘根目录下创建文件iotest1.txt并写入内容
try {
File file1 = new File(filePath1);
FileWriter writer = new FileWriter(file1);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// 读取iotest1.txt的内容并显示
try {
File file1 = new File(filePath1);
FileReader reader = new FileReader(file1);
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// 将iotest1.txt的内容拷贝到iotest2.txt
try {
File file1 = new File(filePath1);
File file2 = new File(filePath2);
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码实现了以下功能:
1. 在E盘根目录下创建文件名为iotest1.txt
2. 将“outputstream”写入iotest1.txt
3. 读取iotest1.txt的内容并显示
4. 将iotest1.txt的内容拷贝到E盘根目录下,文件名为iotest2.txt
阅读全文