Java program to merge two files into a third file

Java 8Server Side ProgrammingProgramming

Following is the Java program to merge two files into a third file −

Example

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.

A class named Demo contains the main function. Here an instance of the PrintWriter class and BufferedReader is generated. Every line in the two files is read, until it reaches null. It is then added to the third file, and the class instances are flushed and closed.

raja
Published on 14-Sep-2020 08:29:28
Advertisements