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
import java.io.*;
class sample {
public static void main(String[] args) throws IOException
{
File dir = new File( "F:\\GeeksForGeeks" );
PrintWriter pw = new PrintWriter( "output.txt" );
String[] fileNames = dir.list();
for (String fileName : fileNames) {
System.out.println( "Reading from " + fileName);
File f = new File(dir, fileName);
BufferedReader br = new BufferedReader( new FileReader(f));
pw.println( "Contents of file " + fileName);
String line = br.readLine();
while (line != null ) {
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:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
25 Aug, 2021
Like Article
Save Article