Merge Two Files into a Third File in Java



In this article, we will learn to merge two files into a third file in Java. Combining the contents of two files into a third file is a typical operation in file handling, frequently needed to aggregate data. Java offers efficient facilities such as BufferedReader and PrintWriter to accomplish this easily.

Approach

The following are the steps to merge the contents of two files into a third file in Java?
  • Read the contents of the first file line by line using a BufferedReader.
  • Write each line to the third file using a PrintWriter.
  • Repeat steps 1 and 2 for the second file.
  • Close all the streams to ensure that the data is properly written to the third file.

Creating a PrintWriter to write to the output file ?

PrintWriter my_pw = new PrintWriter(outputFilePath);

Create a BufferedReader to read from the first file ?

BufferedReader my_br = new BufferedReader(new FileReader(file1Path));
String my_line = my_br.readLine();

Read and write the contents of the first file using println() and readline() ?

while (my_line != null) {
         my_pw.println(my_line);
         my_line = my_br.readLine();
      }

Close the BufferedReader for the first file ?

my_br.close();

Flush and close the PrintWriter ?

my_pw.flush();
my_pw.close();

Example

Below is an example to merge two files into a third file ?

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.");
   }
}

Output

The first two files have been merged into the third file successfully..

Time Complexity: O(n + m), where n and m are the sizes of the two input files.
Space Complexity: O(1), as the program only uses a constant amount of space to store the file readers and writers.

Conclusion

It is straightforward to combine two files into a third file using Java. We read the contents of both files line by line and write to a new file. Using BufferedReader for optimal reading and PrintWriter for optimal writing, we provide the best performance.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-20T18:18:43+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements