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:
- Create instance of directory.
- Create a PrintWriter object for “output.txt”.
- Get list of all the files in form of String Array.
- Loop for reading the contents of all the files in the directory GeeksForGeeks.
- Inside the loop for every file do
-
- Create instance of file from Name of the file stored in string Array.
- Create object of BufferedReader for reading from current file.
- Read from current file.
- Write to the output file.
Java
// 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 object 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: