📜  Java程序将两个文件交替合并到第三个文件中

📅  最后修改于: 2022-05-13 01:55:00.693000             🧑  作者: Mango

Java程序将两个文件交替合并到第三个文件中

先决条件: PrintWriter , BufferedReader

让给定的两个文件是 file1.txt 和 file2.txt。我们的任务是将两个文件合并到第三个文件中,比如 file3.txt,但合并应该逐行完成。以下是交替合并的步骤。

  1. 为 file3.txt 创建 PrintWriter 对象
  2. 为 file1.txt 打开 BufferedReader
  3. 为 file2.txt 打开 BufferedReader
  4. 运行循环以复制 file1.txt 的每一行,然后将 file2.txt 复制到 file3.txt
  5. 刷新 PrintWriter 流并关闭资源。

要成功运行以下程序 file1.txt 和 file2.txt 必须在同一文件夹中退出或为它们提供完整路径。

// Java program to merge two 
// files  into third file alternatively
  
import java.io.*;
  
public class FileMerge 
{
    public static void main(String[] args) throws IOException 
    {
        // PrintWriter object for file3.txt
        PrintWriter pw = new PrintWriter("file3.txt");
          
        // BufferedReader object for file1.txt
        BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
        BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));
          
          
        String line1 = br1.readLine();
        String line2 = br2.readLine();
          
        // loop to copy lines of 
        // file1.txt and file2.txt 
        // to  file3.txt alternatively
        while (line1 != null || line2 !=null)
        {
            if(line1 != null)
            {
                pw.println(line1);
                line1 = br1.readLine();
            }
              
            if(line2 != null)
            {
                pw.println(line2);
                line2 = br2.readLine();
            }
        }
      
        pw.flush();
          
        // closing resources
        br1.close();
        br2.close();
        pw.close();
          
        System.out.println("Merged file1.txt and file2.txt 
alternatively into file3.txt");
    }
}

输出:

Merged file1.txt and file2.txt into file3.txt

注意:如果 cwd(当前工作目录)中存在 file3.txt,那么它将被上面的程序覆盖,否则将创建新文件。