Java program to merge two files alternatively into third file

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 but merging should be done by line by line alternatively. The following are steps to merge alternatively.

  1. Create PrintWriter object for file3.txt
  2. Open BufferedReader for file1.txt
  3. Open BufferedReader for file2.txt
  4. Run a loop to copy each line of file1.txt and then file2.txt to file3.txt
  5. 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 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 :If file3.txt exist in cwd(current working directory) then it will be overwritten by above program otherwise new file will be created.

Related Articles :

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.

GeeksforGeeks责编内容来自:GeeksforGeeks (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java program to merge two files alternatively into third file

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录