java字符流将文件t1.txt和文件t2.txt的内容读取并输出;将t1.txt和t2.txt的内容合并到新的t3.txt中;输出文件t3.txt的内容。
时间: 2024-05-10 12:02:02 浏览: 133
以下是Java代码实现:
```
import java.io.*;
public class MergeFilesDemo {
public static void main(String[] args) {
try {
// 读取文件t1.txt
FileReader reader1 = new FileReader("t1.txt");
BufferedReader br1 = new BufferedReader(reader1);
String line1 = br1.readLine();
while (line1 != null) {
System.out.println(line1);
line1 = br1.readLine();
}
br1.close();
reader1.close();
// 读取文件t2.txt
FileReader reader2 = new FileReader("t2.txt");
BufferedReader br2 = new BufferedReader(reader2);
String line2 = br2.readLine();
while (line2 != null) {
System.out.println(line2);
line2 = br2.readLine();
}
br2.close();
reader2.close();
// 合并文件t1.txt和t2.txt到t3.txt
FileWriter writer = new FileWriter("t3.txt");
FileReader reader3 = new FileReader("t1.txt");
BufferedReader br3 = new BufferedReader(reader3);
String line3 = br3.readLine();
while (line3 != null) {
writer.write(line3);
writer.write("\n"); // 换行
line3 = br3.readLine();
}
br3.close();
reader3.close();
FileReader reader4 = new FileReader("t2.txt");
BufferedReader br4 = new BufferedReader(reader4);
String line4 = br4.readLine();
while (line4 != null) {
writer.write(line4);
writer.write("\n"); // 换行
line4 = br4.readLine();
}
br4.close();
reader4.close();
writer.close();
// 读取文件t3.txt
FileReader reader5 = new FileReader("t3.txt");
BufferedReader br5 = new BufferedReader(reader5);
String line5 = br5.readLine();
while (line5 != null) {
System.out.println(line5);
line5 = br5.readLine();
}
br5.close();
reader5.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码会依次读取文件t1.txt和t2.txt的内容并输出,然后将这两个文件的内容合并到新的t3.txt文件中,并最后输出文件t3.txt的内容。
阅读全文