Your code should be

Scanner input1 = new Scanner(new File(firstName));//read first file
Scanner input2 = new Scanner(new File(secondName));//read second file

while(input1.hasNextLine() && input2.hasNextLine()){
    first = input1.nextLine();   
    second = input2.nextLine(); 

    if(!first.equals(second)){
        System.out.println("Differences found: "+"\n"+first+'\n'+second);
    }
}

// optionally handle any remaining lines if the line count differs

Previously you only compared one time, the very last line. But you need to compare after each line you read.

Answer from luk2302 on Stack Overflow
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ compare-two-different-files-line-by-line-in-java
Compare Two Different Files Line by Line in Java
else { System.out.println("Both the files have different content"); System.out.println("In both files, there is a difference at line number: "+lineNum); System.out.println("One file has "+line1+" and another file has "+line2+" at line "+lineNum); } reader1.close(); reader2.close(); } } Both the files have different content In both files, there is a difference at line number: 2 One file has Java Language.
๐ŸŒ
Java Concept Of The Day
javaconceptoftheday.com โ€บ home โ€บ how to compare two text files in java?
How To Compare Two Text Files Line By Line In Java?
November 16, 2016 - They differ at line "+lineNum); System.out.println("File1 has "+line1+" and File2 has "+line2+" at line "+lineNum); } reader1.close(); reader2.close(); } } ... Two files have same content. ... Two files have different content. They differ at line 4 File1 has Vikas 92 and File2 has Nalini 62 at line 4 ... what if the files have multiple differences??? The above programme only point outs the first difference.
Top answer
1 of 3
3

HashMap solution

I thought about it and the HashMap solution is instant. I went ahead and coded up an example of it here.

It runs in 0ms while the arrayLists ran in 16ms for the same dataset

public static void main(String[] args) throws Exception {
    BufferedReader br1 = null;
    BufferedReader br2 = null;
    BufferedWriter bw3 = null;
    String sCurrentLine;
    int linelength;

    HashMap<String, Integer> expectedrecords = new HashMap<String, Integer>();
    HashMap<String, Integer> actualrecords = new HashMap<String, Integer>();

    br1 = new BufferedReader(new FileReader("expected.txt"));
    br2 = new BufferedReader(new FileReader("actual.txt"));

    while ((sCurrentLine = br1.readLine()) != null) {
        if (expectedrecords.containsKey(sCurrentLine)) {
            expectedrecords.put(sCurrentLine, expectedrecords.get(sCurrentLine) + 1);
        } else {
            expectedrecords.put(sCurrentLine, 1);
        }
    }
    while ((sCurrentLine = br2.readLine()) != null) {
        if (expectedrecords.containsKey(sCurrentLine)) {
            int expectedCount = expectedrecords.get(sCurrentLine) - 1;
            if (expectedCount == 0) {
                expectedrecords.remove(sCurrentLine);
            } else {
                expectedrecords.put(sCurrentLine, expectedCount);
            }
        } else {
            if (actualrecords.containsKey(sCurrentLine)) {
                actualrecords.put(sCurrentLine, actualrecords.get(sCurrentLine) + 1);
            } else {
                actualrecords.put(sCurrentLine, 1);
            }
        }
    }

    // expected is left with all records not present in actual
    // actual is left with all records not present in expected
    bw3 = new BufferedWriter(new FileWriter(new File("c.txt")));
    bw3.write("Records which are not present in actual\n");
    for (String key : expectedrecords.keySet()) {
        for (int i = 0; i < expectedrecords.get(key); i++) {
            bw3.write(key);
            bw3.newLine();
        }
    }
    bw3.write("Records which are in actual but not present in expected\n");
    for (String key : actualrecords.keySet()) {
        for (int i = 0; i < actualrecords.get(key); i++) {
            bw3.write(key);
            bw3.newLine();
        }
    }
    bw3.flush();
    bw3.close();
}

ex:

expected.txt

one
two
four
five
seven
eight

actual.txt

one
two
three
five
six

c.txt

Records which are not present in actual
four
seven
eight
Records which are in actual but not present in expected
three
six

ex 2:

expected.txt

one
two
four
five
seven
eight
duplicate
duplicate
duplicate

actual.txt

one
duplicate
two
three
five
six

c.txt

Records which are not present in actual
four
seven
eight
duplicate
duplicate
Records which are in actual but not present in expected
three
six
2 of 3
1

In Java 8 you can use Collection.removeIf(Predicate<T>)

list1.removeIf(line -> list2.contains(line));
list2.removeIf(line -> list1.contains(line));

list1 will then contain everything that is NOT in list2 and list2 will contain everything, that is NOT in list1.

๐ŸŒ
Its All Binary
itsallbinary.com โ€บ home โ€บ compare files side by side and hightlight diff using java | apache commons text diff | myers algorithm
Compare files side by side and hightlight diff using Java | Apache Commons Text diff | Myers algorithm - Its All Binary - Coding Posts, Examples, Projects & More
March 10, 2020 - In this article we will create a simple basic file diff tool/program using Apache commons text library & output diff in HTML. Take 2 text file as input i.e. file-1.txt & file-2.txt ยท Compare both files using Apache commons text & generate HTML ...
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ java โ€บ comparing files in java
Comparing Files in Java
February 1, 2018 - package packt.java9.network.niodemo; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; public class SampleCompare { public static void main(String[] args) throws IOException { long start = System.nanoTime(); BufferedInputStream fis1 = new BufferedInputStream(new FileInputStream("sample.txt")); BufferedInputStream fis2 = new BufferedInputStream(new FileInputStream("sample-copy.txt")); int b1 = 0, b2 = 0, pos = 1; while (b1 != -1 && b2 != -1) { if (b1 != b2) { System.out.println("Files differ at position " + pos); } pos++; b1 = fis1.read(); b2 = fis2
๐ŸŒ
DevGlan
devglan.com โ€บ corejava โ€บ comparing-files-in-java
Comparing Files In Java | DevGlan
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CompareTextFiles { public static void main(String[] args) throws IOException { BufferedReader reader1 = new BufferedReader(new FileReader("C:\\file1.txt")); BufferedReader reader2 = new BufferedReader(new FileReader("C:\\file2.txt")); String line1 = reader1.readLine(); String line2 = reader2.readLine(); boolean areEqual = true; int lineNum = 1; while (line1 != null || line2 != null) { if(line1 == null || line2 == null) { areEqual = false; break; } else if(! line1.equalsIgnoreCase(line2)) { areEqu
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 480861 โ€บ java โ€บ Compare-Text-Files
Compare Two Text Files (Beginning Java forum at Coderanch)
For example if the content of the two text files are as below, the actual output should be " A friendly place for Java greenhorns", where as the out put i get is "place". What changes should i made to the existing code? Comments are appreciated. ... Why should the output be what you show above? What are you trying to accomplish? In any case: you're printing the line if the two lines, one from each file, are the same.
Find elsewhere
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 672590 โ€บ java โ€บ Compare-huge-text-files-java
Compare two huge text files in java and get non matching records (Java in General forum at Coderanch)
If this was my problem, I'd start by using one of the existing diff utilities -which you can invoke from within Java-, and then work on its output.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 40519130 โ€บ java-comparing-two-huge-text-files
arrays - Java - Comparing two huge text files - Stack Overflow
import java.io.*; public class CompareTwoFiles { static int count1 = 0 ; static int count2 = 0 ; static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")]; static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")]; public static void main(String args[]){ findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt"); displayRecords(); } public static int countLines(String File){ int lineCount = 0; try { BufferedReader br = new BufferedReader(new FileReader(File)); while ((br.readLine()) != null) { lineCount++; } } catch (
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ compare the content of two files in java
Compare the Content of Two Files in Java | Baeldung
January 8, 2024 - If the files are of different sizes but the smaller file matches the corresponding lines of the larger file, then it returns the number of lines of the smaller file. The method Files::mismatch, added in Java 12, compares the contents of two files.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ java compare files
How to Compare Content of Two Files in Java | Delft Stack
February 2, 2024 - package delftstack; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class File_Compare { public static void main(String[] args) throws IOException { File File_One = new File("delftstack1.txt"); File File_Two = new File("delftstack2.txt"); File File_Three = new File("delftstack3.txt"); long Compare1 = Files.mismatch(File_One.toPath(), File_Two.toPath()); System.out.println(Compare1); long Compare2 = Files.mismatch(File_Two.toPath(), File_Three.toPath()); System.out.println(Compare2); } }
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2014 โ€บ 08 โ€บ how-to-compare-two-files-in-eclipse-differences-text.html
How to see difference between two Files in Eclipse - Text Comparison Example Tutorial
and here is the output of text comparison in Eclipse : This discovery actually motivates me to continue my run of discovering full potential of Eclipse IDE. Right now, I use Eclipse as for writing Java code, running and debugging Java program, running unit tests, running DOS commands from Eclipse, seeing differences between different version of same file under source control e.g.
๐ŸŒ
TextCompare
textcompare.org โ€บ java
Online Java Compare Tool
Find difference between 2 text files. Just input or paste original and modified text and click Compare button. Fast, Private & Unlimited.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 67801698 โ€บ java-comparing-two-text-files-and-writing-diffs
Java comparing two text files and writing diffs - Stack Overflow
As per your comment, you want to detect all differences between the two files. For this, you either need to store all occurrences in a data-structure and loop over this later (to print) when the files are not equal.