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


To merge contents of all the files in a directory, the Java code is as follows −

Example

import java.io.*;
public class Demo{
   public static void main(String[] args) throws IOException{
      File my_dir = new File("path to place where file is generated");
      PrintWriter my_writer = new PrintWriter("The .txt where changes are stored");
      String[] file_names = my_dir.list();
      for (String file_names : fileNames){
         System.out.println("Content read from " + file_names);
         File my_file = new File(my_dir, file_names);
         BufferedReader my_reader = new BufferedReader(new FileReader(my_file));
         my_writer.println("The file contains " + file_names);
         String my_line = my_reader.readLine();
         while (my_line != null){
            my_writer.println(my_line);
            my_line = my_reader.readLine();
         }
         my_writer.flush();
      }
      System.out.println("All data from files have been read and " + my_dir.getName() + "merged");
   }
}

Output

All file contents will be merged into a single text file.

A class named Demo contains the main function. A new file type is created and the location of the place where the new file needs to be created is passed as parameter to it.

A PrintWriter instance is created and names of files present in the directory is stored in a string array. The file names are iterated over, and read using BufferedReader instance. Whatever is read is written into the new file and stored. The Writer is also flushed so that no residue is left out.

Updated on: 14-Jul-2020

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements