Let the given two files be file1.txt and file2.txt. Our task is to merge the two files into a third file in java, such as file3.txt. The following are the merge steps.
In order to run the following java program successfully, file1.txt and file2.txt must go to the same folder OR provide the full path for the program.
// 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 :
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.