Thursday, February 29, 2024

Java program to merge two text files in to third file.

import java.io.*;

public class MergeFiles {
    public static void main(String[] args) {
        String inputFile1 = "inputFile1.txt"; // Replace with the actual file path and name
        String inputFile2 = "inputFile2.txt"; // Replace with the actual file path and name
        String outputFile = "outputFile.txt"; // Replace with the desired output file path and name

        mergeFiles(inputFile1, inputFile2, outputFile);

        System.out.println("Files merged successfully!");
    }

    private static void mergeFiles(String inputFile1, String inputFile2, String outputFile) {
        try (BufferedReader reader1 = new BufferedReader(new FileReader(inputFile1));
             BufferedReader reader2 = new BufferedReader(new FileReader(inputFile2));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

            String line;

            // Merge content from inputFile1
            while ((line = reader1.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }

            // Merge content from inputFile2
            while ((line = reader2.readLine()) != null) {
                writer.write(line);
                writer.newLine();
            }

        } catch (IOException e) {
            System.err.println("Error merging files: " + e.getMessage());
        }
    }
}

No comments:

Post a Comment

Java program to implement file input stream class to read binary data from image file.

import java.io.FileInputStream; import java.io.IOException; public class ReadImageFile {     public static void main(String[] args) {       ...