Java program to merge contents of all the files in a directory

Prerequisite : PrintWriter, BufferedReader.
We are given a directory/folder in which n number of files are stored(We dont know the number of files) and we want to merge the contents of all the files into a single file lets say output.txt
For the below example lets say the folder is stored at the path: F:\GeeksForGeeks

Following are the steps:

  1. Create instance of directory.
  2. Create a PrintWriter object for “output.txt”.
  3. Get list of all the files in form of String Array.
  4. Loop for reading the contents of all the files in the directory GeeksForGeeks.
  5. Inside the loop for every file do
    1. Create instance of file from Name of the file stored in string Array.
    2. Create object of BufferedReader for reading from current file.
    3. Read from current file.
    4. Write to the output file.




// Java program to merge all files of a directory
class sample {
    public static void main(String[] args) throws IOException
        // create instance of directory
        File dir = new File("F:\\GeeksForGeeks");
        // create obejct of PrintWriter for output file
        PrintWriter pw = new PrintWriter("output.txt");
        // Get list of all the files in form of String Array
        String[] fileNames = dir.list();
        // loop for reading the contents of all the files 
        // in the directory GeeksForGeeks
        for (String fileName : fileNames) {
            System.out.println("Reading from " + fileName);
            // create instance of file from Name of 
            // the file stored in string Array
            File f = new File(dir, fileName);
            // create object of BufferedReader
            BufferedReader br = new BufferedReader(new FileReader(f));
            pw.println("Contents of file " + fileName);
            // Read from current file
            String line = br.readLine();
            while (line != null) {
                // write to the output file
                line = br.readLine();
        System.out.println("Reading from all files"
        " in directory " + dir.getName() + " Completed");


Contents of folder F\GeeksForGeeks

Contents of 3 files in GeeksForGeeks folder:

Output file:

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.