How do I merge the content of files in Java?

You can merge file contents in Java using the following steps:

  1. Create an output stream to write the merged file content.
  2. Read each file to be merged one by one, and write its contents into the output stream.
  3. Close the input and output streams.

Here is an example code:

import java.io.*;

public class FileMerger {
    public static void main(String[] args) {
        try {
            File outputFile = new File("output.txt");
            FileOutputStream fos = new FileOutputStream(outputFile);

            File[] filesToMerge = {new File("file1.txt"), new File("file2.txt")};

            for (File file : filesToMerge) {
                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, length);
                }
                fis.close();
            }
            
            fos.close();
            System.out.println("Files merged successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the code above, we first create an output file named output.txt and use FileOutputStream to write the merged content. Then, we create an array containing the files to be merged, read the content of each file one by one, and write it to the output file. Finally, we close the input and output streams.

Please note that the code above is just a simple example, actual applications may require handling more exceptions and edge cases.

bannerAds