Prerequisite : PrintWriter , BufferedReader
Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt. The following are steps to merge.
- Create PrintWriter object for file3.txt
- Open BufferedReader for file1.txt
- Run a loop to copy each line of file1.txt to file3.txt
- Open BufferedReader for file2.txt
- Run a loop to copy each line of file2.txt to file3.txt
- Flush PrintWriter stream and close resources.
To successfully run the below program file1.txt and file2.txt must exits in same folder OR provide full path for them.
// Java program to merge two // files into third file 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 br = new BufferedReader(new FileReader("file1.txt")); String line = br.readLine(); // loop to copy each line of // file1.txt to file3.txt while (line != null) { pw.println(line); line = br.readLine(); } br = new BufferedReader(new FileReader("file2.txt")); line = br.readLine(); // loop to copy each line of // file2.txt to file3.txt while(line != null) { pw.println(line); line = br.readLine(); } pw.flush(); // closing resources br.close(); pw.close(); System.out.println("Merged file1.txt and file2.txt into file3.txt"); } } |
Output:
Merged file1.txt and file2.txt into file3.txt
Note : If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.
Related Article :
- C Program to merge contents of two files into a third file
- Java program to merge two files alternatively into third file
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Java program to merge two files alternatively into third file
- Java program to merge two files alternatively into third file
- Java program to List all files in a directory and nested sub-directories | Recursive approach
- Java program to delete certain text from a file
- Java program to delete duplicate lines in text file
- Java program to read all mobile numbers present in given file
- Jar files in Java
- How to rename all files of a folder using Java?
- Compressing and Decompressing files in Java
- Working with JAR and Manifest files In Java
- Compressing and Decompressing files using GZIP Format in java
- Merge two sets in Java
- StringJoiner merge() method in Java
- Merge arrays into a new object array in Java
- File Permissions in Java



