编写程序,选用字符缓冲流,实现下述要求: (1)输出文件test1.txt内容; (2)将test1.txt的内容复制到test2.txt中; (3)输出文件test2.txt内容Java
时间: 2023-06-18 16:08:08 浏览: 111
下面是Java代码实现:
```java
import java.io.*;
public class CharBufferDemo {
public static void main(String[] args) {
try {
// 读取test1.txt文件内容
BufferedReader reader = new BufferedReader(new FileReader("test1.txt"));
String line;
System.out.println("test1.txt内容:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
// 将test1.txt的内容复制到test2.txt中
BufferedWriter writer = new BufferedWriter(new FileWriter("test2.txt"));
reader = new BufferedReader(new FileReader("test1.txt"));
System.out.println("test2.txt内容:");
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
System.out.println(line);
}
reader.close();
writer.close();
// 输出test2.txt文件内容
reader = new BufferedReader(new FileReader("test2.txt"));
System.out.println("test2.txt内容:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,此处使用了try-catch语句处理可能发生的IO异常。同时,在写入test2.txt文件时,需要调用`write()`方法写入每行内容,并且在每行结尾处调用`newLine()`方法换行。
阅读全文