Merge Multiple Files Alternately

JavaJavaBeginner
Practice Now

Introduction

In this project, you will learn how to merge multiple text files by lines in an alternating manner. This is a common task in data processing and file management, where you may need to combine content from several files into a single file.

ðŸŽŊ Tasks

In this project, you will learn:

  • How to prepare the necessary input files for the file merging process
  • How to implement a function to merge the contents of the input files
  • How to run the file merging process and verify the output

🏆 Achievements

After completing this project, you will be able to:

  • Work with file I/O operations in Java, including reading from and writing to files
  • Use Java's built-in file and stream classes to handle file operations
  • Implement a custom file merging algorithm to combine the contents of multiple files
  • Test and verify the correctness of the file merging process

Implement the Merge Function

In this step, you will implement the merge function to merge the contents of the input files.

  1. Open the FileMerge.java file in the /home/labex/project directory.

  2. Locate the merge function and replace the existing code with the following implementation:

public static void merge(String[] sourcePath, String outPath) throws IOException {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outPath))) {
        BufferedReader[] readers = new BufferedReader[sourcePath.length];
        String[] currentLines = new String[sourcePath.length];
        boolean[] fileEmpty = new boolean[sourcePath.length];

        // Open readers for each source file
        for (int i = 0; i < sourcePath.length; i++) {
            readers[i] = new BufferedReader(new FileReader(sourcePath[i]));
            currentLines[i] = readers[i].readLine();
            fileEmpty[i] = (currentLines[i] == null);
        }

        // Merge lines from each file
        boolean allFilesEmpty = false;
        while (!allFilesEmpty) {
            allFilesEmpty = true;
            for (int i = 0; i < sourcePath.length; i++) {
                if (!fileEmpty[i]) {
                    writer.write(currentLines[i]);
                    writer.newLine();
                    currentLines[i] = readers[i].readLine();
                    fileEmpty[i] = (currentLines[i] == null);
                    allFilesEmpty = false;
                }
            }
        }

        // Close readers
        for (BufferedReader reader : readers) {
            reader.close();
        }
    }
}

This implementation opens a BufferedReader for each input file, reads the lines from each file, and writes the lines to the output file in an alternating manner. If a file has no more lines, it is skipped until all the lines from all files have been written to the output file.

âœĻ Check Solution and Practice

Run the File Merging Process

In this step, you will run the file merging process and verify the output.

  1. Open the FileMerge.java file in the /home/labex/project directory.

  2. Locate the main function and make sure the strs array contains the names of the input files: "1.txt", "2.txt", and "3.txt".

  3. Run the FileMerge class by executing the following command in the terminal:

javac FileMerge.java
java FileMerge
  1. After the program runs successfully, a new file named 0.txt will be created in the /home/labex/project directory. This file will contain the merged content from the input files.

  2. Open the 0.txt file and verify that the content matches the expected output:

1
6
7
2
8
3
9
4
5

Congratulations! You have successfully completed the file merging project.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like