先决条件: PrintWriterBufferedReader

让给定的两个文件是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流并关闭资源。

Java程序将两个txt文件合并为第三个txt文件的示例

要成功运行以下程序,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

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

 
转载请保留页面地址:https://www.breakyizhan.com/java/5020.html