Leave the given two documents alone file1.txt and file2.txt. Our Task is to blend the two records into third document say file3.txt yet combining ought to be finished by line by line then again. Coming up next are steps to combine on the other hand.
To effectively run the beneath program file1.txt and file2.txt must ways out in same organizer OR give full way to them.
// 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"); } }
Output:
Merged file1.txt and file2.txt into file3.txt
Note : In the event that file3.txt exist in cwd(current working index) it will be overwritten by above program in any case new record will be made.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.