Skip to content
Related Articles

Related Articles

Improve Article
Java program to merge contents of all the files in a directory
  • Difficulty Level : Medium
  • Last Updated : 22 Dec, 2018

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
import java.io.*;
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
                pw.println(line);
                line = br.readLine();
            }
            pw.flush();
        }
        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 Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :