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



In this article, we will learn how to merge the contents of all the text files in a directory into a single file using Java. It reads the data from each file and writes it into a new file while ensuring all data is stored in an organized manner. You'll see how to handle files, read their content, and merge them programmatically.

File class

The java.io package contains the Java File classwhich provides an abstract representation of file and directory pathnames. It is commonly used for creating files and directories, searching for files, deleting files, and performing other file-related operations.

File my_file = new File(my_dir, file_name);

A File object represents a specific file or directory on the disk.

BufferedReader class

The BufferedReader class is designed to read text efficiently from a character input stream by buffering data. It allows reading characters, arrays, or entire lines, making it ideal for handling larger text data while minimizing I/O operations. This buffering mechanism improves performance compared to reading directly from the stream.

BufferedReader my_reader = new BufferedReader(new FileReader(my_file));

list() methodThis method is used to get the names of all files inside the specified directory (my_dir). The file names are stored in the file_names array, which will later be iterated over to read the content of each file.

String[] file_names = my_dir.list();

PrintWriter class

The java.io.PrintWriter class is used to write formatted text to an output stream, supporting strings, characters, and other data types. It also allows automatic line flushing for easier text file creation.

We will be using the flush() method from the PrintWriter class:

my_writer.flush();

 The flush() method ensures that all data in the buffer is written to the file.

Merging the contents of all the files in a directory

Following are the steps to merge the contents of all the files in a directory ?

  • Set Up File Handling:
    Create a File object to represent the directory containing the text files we will use the list() method of the File class to get all file names in the directory and will create a PrintWriter object to write the merged content into a new file.
  • Read and Write File Contents:
    Use a BufferedReader to read its content line by line and write the content to the new file using PrintWriter.
  • Finalize:
    Use the flush() method of PrintWriter to ensure all data is written to the output file.

Example

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

import java.io.*; // Importing classes for file handling
public class Demo {
    public static void main(String[] args) throws IOException {
        // Specify the directory where files are located
        File my_dir = new File("path to place where file is generated");

        // Create a PrintWriter to write the merged content into a new file
        PrintWriter my_writer = new PrintWriter("The .txt where changes are stored");

        // Get a list of all file names in the specified directory
        String[] file_names = my_dir.list();

        // Loop through each file name in the directory
        for (String file_name : file_names) {
            // Print the name of the file being read
            System.out.println("Content read from " + file_name);

            // Create a File object for the current file
            File my_file = new File(my_dir, file_name);

            // Create a BufferedReader to read the content of the file
            BufferedReader my_reader = new BufferedReader(new FileReader(my_file));

            // Write the file name as a header in the output file
            my_writer.println("The file contains " + file_name);

            // Read the content of the file line by line
            String my_line = my_reader.readLine();
            while (my_line != null) {
                // Write each line into the output file
                my_writer.println(my_line);

                // Read the next line
                my_line = my_reader.readLine();
            }

            // Flush the writer to ensure all content is written
            my_writer.flush();
        }

        // Print confirmation message after all files are merged
        System.out.println("All data from files have been read and merged into " + my_dir.getName());
    }
}

Output

All file contents will be merged into a single text file.
Updated on: 2024-11-20T22:39:25+05:30

913 Views

Kickstart Your Career

Get certified by completing the course

Get Started