Merge Files in Java

I often need to merge multiple files into one in Java. So I write a reusable method to do this job. It works very well for me to merge a set of txt files.

The method accepts an array of File and the merged file path. After running the method, the set of files to be merged will be merged into the specified file.

package com.programcreek;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class MergerFiles {
 
	public static void main(String[] args) {
		String sourceFile1Path = "/home/programcreek/Desktop/s1";
		String sourceFile2Path = "/home/programcreek/Desktop/s2";
 
		String mergedFilePath = "/home/programcreek/Desktop/m";
 
		File[] files = new File[2];
		files[0] = new File(sourceFile1Path);
		files[1] = new File(sourceFile2Path);
 
		File mergedFile = new File(mergedFilePath);
 
		mergeFiles(files, mergedFile);
	}
 
	public static void mergeFiles(File[] files, File mergedFile) {
 
		FileWriter fstream = null;
		BufferedWriter out = null;
		try {
			fstream = new FileWriter(mergedFile, true);
			 out = new BufferedWriter(fstream);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
 
		for (File f : files) {
			System.out.println("merging: " + f.getName());
			FileInputStream fis;
			try {
				fis = new FileInputStream(f);
				BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 
				String aLine;
				while ((aLine = in.readLine()) != null) {
					out.write(aLine);
					out.newLine();
				}
 
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
		try {
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
	}
}

Output:

merging: s1
merging: s2
Category >> I/O  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Dan

    Can this be done with files other than text files? Say word documents or Excel documents for example?

  • When I merge 10 large files (around 180 MB each) using your program, merge file size increase by 4KB from expected 🙂

  • JacobC

    This was great exactly what I needed!!! To build upon this you can also merge all of the files in an entire directory. I did this by incorporating the following method into your code.

    public static File[] getAllLogFiles(){
    File folder = new File(“path/toYour/dir”);
    File[] files = folder.listFiles();
    }
    return files;
    }

    Thanks again for this post!