将两个文件合并到第三个文件中的 Java 程序
以下是将两个文件合并到第三个文件中的 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("The first two files have been merged into the third file successfully."); } }
输出
The first two files have been merged into the third file successfully.
一个名为 Demo 的类包含主函数。在这里生成了 PrintWriter 类和 BufferedReader 的一个实例。依次读取两个文件中每一行内容,直到到达 null。然后将内容添加到第三个文件,并刷新和关闭类实例。
广告