Java program to alternately merge two or more files into a third file
Suppose we have three files -
output1.txt
Hello how are you
output2.txt
Welcome to Tutorialspoint
output3.txt
We provide simply easy learning
Example
The following Java example alternately merges the contents of the above three files into one file-
import java.util.Scanner; public class MergingFiles { public static void main(String args[]) throws IOException { Scanner sc1 = new Scanner(new File("D://input1.txt")); Scanner sc2 = new Scanner(new File("D://input2.txt")); Scanner sc3 = new Scanner(new File("D://input3.txt")); FileWriter writer = new FileWriter("D://result.txt"); String str[] = new String[3]; while (sc1.hasNextLine()||sc2.hasNextLine()||sc3.hasNextLine()) { str[0] = sc1.nextLine(); str[1] = sc2.nextLine(); str[2] = sc3.nextLine(); } writer.append(str[0]+"\n"); writer.append(str[1]+"\n"); writer.append(str[2]+"\n"); writer.flush(); System.out.println("Contents added "); } }
Output
Contents added
If the above three files are directly in the same file, you can rewrite the example program as -
Example
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class MergingFiles { public static void main(String args[]) throws IOException { //Creating a File object for directory File directoryPath = new File("D:\example"); //List of all files and directories File filesList[] = directoryPath.listFiles(); Scanner sc = null; FileWriter writer = new FileWriter("D://output.txt"); for(File file : filesList) { sc = new Scanner(file); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); writer.append(input+"\n"); } writer.flush(); } System.out.println("Contents added "); } }
Output
Contents added
The above is the detailed content of Java program to alternately merge two or more files into a third file. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor