Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.6 kB
7
Indexable
Never
package org.example;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileCompare {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a first file name: ");
        String file1 = scanner.nextLine();
        System.out.print("Enter a second file name: ");
        String file2 = scanner.nextLine();

        compareFiles(file1, file2);
    }

    private static void compareFiles(String file1, String file2) {
        try (BufferedReader br1 = new BufferedReader(new FileReader(file1));
             BufferedReader br2 = new BufferedReader(new FileReader(file2))) {

            String line1 = br1.readLine();
            String line2 = br2.readLine();
            int lineNum = 1;

            while (line1 != null || line2 != null) {
                if (line1 == null || line2 == null || !line1.equals(line2)) {
                    System.out.println("Difference found:");
                    System.out.println("Line " + lineNum + ":");
                    if (line1 != null) {
                        System.out.println("< " + line1);
                    }
                    if (line2 != null) {
                        System.out.println("> " + line2);
                    }
                }
                line1 = br1.readLine();
                line2 = br2.readLine();
                lineNum++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Leave a Comment