Merge Multiple Files in Java: Explanation & Practice

Merge contents of multiple files

Problem summary

Merge the contents of multiple text files into one output file.

Starter code

import java.io.*;

public class Main {
    public static void main(String[] args) {
        String[] files = {"file1.txt", "file2.txt", "file3.txt"};
        
        // Merge all files into merged.txt
        // Print: Merged <count> files
    }
}

Expected output and test cases

  • Three files merged
    Merged 3 files
  • Single file
    Merged 1 files
  • Five files
    Merged 5 files

Hints

  1. Open output file once
  2. Loop through input files
  3. Append each file's content

Related File I/O exercises

Practice all File I/O exercises · Run this idea in the Java compiler