將兩個檔案合併到第三個檔案中的 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。然後將內容新增到第三個檔案,並重新整理和關閉類例項。

更新於: 14-9-2020

3K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.