以下是将两个文件合并为第三个文件的Java程序-
import java.io.*; public class Demo { public static void main(String[] args) throws IOException { PrintWriter my_pw = new PrintWriter("path to third .txt file"); BufferedReader my_br = new BufferedReader(new FileReader("path to first .txt file")); String my_line = my_br.readLine(); while (my_line != null) { my_pw.println(my_line); my_line = my_br.readLine(); } my_br = new BufferedReader(new FileReader("path to second .txt file")); my_line = my_br.readLine(); while(my_line != null) { my_pw.println(my_line); my_line = my_br.readLine(); } my_pw.flush(); my_br.close(); my_pw.close(); System.out.println("前两个文件已成功合并到第三个文件。"); } }
输出结果
前两个文件已成功合并到第三个文件。
名为Demo的类包含主要功能。这里生成了PrintWriter类和BufferedReader的实例。读取两个文件中的每一行,直到达到空。然后将其添加到第三个文件,并刷新并关闭类实例。