Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into third file say file3.txt but merging should be done by line by line alternatively. The following are steps to merge alternatively.
- Create PrintWriter object for file3.txt
- Open BufferedReader for file1.txt
- Open BufferedReader for file2.txt
- Run a loop to copy each line of file1.txt and then 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.
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.
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 email@example.com. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Java program to merge two files alternatively into third file
- Java program to merge two files into a third file
- Java program to merge contents of all the files in a directory
- Alternatively Merge two Strings in Java
- Java program to List all files in a directory and nested sub-directories | Recursive approach
- Java program to delete certain text from a file
- Optimal File Merge Patterns
- Java program to read all Emails present in a Given file
- Java program to store a Student Information in a File using AWT
- Java program to read all mobile numbers present in given file
- Java program to delete duplicate lines in text file
- Jar files in Java
- Working with JAR and Manifest files In Java
- Compressing and Decompressing files in Java
- How to rename all files of a folder using Java?
- Files deleteIfExists() method in Java with Examples
- Files delete() method in Java with Examples
- Files size() method in Java with Examples
- Files isWritable() method in Java with Examples
- Files isReadable() method in Java with Examples