Exactly what FileUtils.contentEquals method of Apache commons IO does and api is here.

Try something like:

File file1 = new File("file1.txt");
File file2 = new File("file2.txt");
boolean isTwoEqual = FileUtils.contentEquals(file1, file2);

It does the following checks before actually doing the comparison:

  • existence of both the files
  • Both file's that are passed are to be of file type and not directory.
  • length in bytes should be the same.
  • Both are different files and not one and the same.
  • Then compare the contents.
Answer from SMA on Stack Overflow
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ compare-two-different-files-line-by-line-in-java
Compare Two Different Files Line by Line in Java
Here, we can notice both the files have different content at line-2. As file1, line-2 contains ?Java Language' and file2, line-2 contains ?Python Language' Step 1 ? Create reader1 and reader2 as two BufferedReader objects and use them to read the two input text files line by line.
๐ŸŒ
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 - The methods IOUtils::contentEquals and IOUtils::contentEqualsIgnoreEOL compare the contents of two files to determine equality. The difference between them is that contentEqualsIgnoreEOL ignores line feed (\n) and carriage return (\r).
๐ŸŒ
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 - Step 4 : Keep reading the lines ... then assign false to areEqual and break the loop. If both, line1 and line2, are not null then compare them using equalsIgnoreCase() method....
๐ŸŒ
DevGlan
devglan.com โ€บ corejava โ€บ comparing-files-in-java
Comparing Files In Java | DevGlan
Open your files by using the RandomAccessFile class and ask for the channel from this object if you want to memory map the two files. MappedByteBuffer, a representation of the memory area of your file's contents can be created from the channel ...
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 480861 โ€บ java โ€บ Compare-Text-Files
Compare Two Text Files (Beginning Java forum at Coderanch)
Few corrections FileInputStream fstream2 = new FileInputStream("textfile1.txt"); -> You are reading same file if(strLine1 = strLine2) -> You should use .equals() method to compare two object values. I don't know of any direct aPI whic can be used to compare files directly in java.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ java compare files
How to Compare Content of Two Files in Java | Delft Stack
February 2, 2024 - Similarly, the BufferedInputStream is also used to read the file and compare each line of one file to each line of the other file. We use the readline() method from BufferedReader to read each line and compare it.
Find elsewhere
Top answer
1 of 2
3

You could iterate over these two files line by line using a BufferedReader

the readLine() method returns a string representation of each line which can then be checked for equality.

The index of any unequal lines can be stored and returned in any way you want.

2 of 2
-1
void compareFiles() {
    BufferedReader bfr1 = null;
    BufferedReader bfr2 = null;
    List<String> file1Data = new ArrayList<>();
    List<String> file2Data = new ArrayList<>();
    List<String> matchedLines = new ArrayList<>();
    List<String> unmatchedLines = new ArrayList<>();

    try {
        File file1 = new File("F:/file1.txt");
        File file2 = new File("F:/file2.txt");
        bfr1 = new BufferedReader(new FileReader(file1));
        bfr2 = new BufferedReader(new FileReader(file2));

        String name1;
        String name2;
        try {
            // read the first file and store it in an ArrayList
            while ((name1 = bfr1.readLine()) != null) {
                file1Data.add(name1);
            }
            // read the second file and store it in an ArrayList
            while ((name2 = bfr2.readLine()) != null) {
                file2Data.add(name2);
            }

            // iterate once over the first ArrayList and compare with the second.
            for (String key1 : file1Data) {
                if (file2Data.contains(key1)) { // here is your desired match
                    matchedLines.add(key1);
                } else {
                    unmatchedLines.add(key1);
                }
            }
            System.out
                    .println("Matched Lines are: \n" + matchedLines + "\nUnmatched Lines are: \n" + unmatchedLines);

        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (FileNotFoundException ex) {
        System.out.println(ex);
    } finally {
        try {
            bfr1.close();
            bfr2.close();
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
}
๐ŸŒ
TextCompare
textcompare.org โ€บ java
Online Java Compare Tool
Just click Compare button to view side by side comparison. View the differences highlighted in colors. Privacy: This tool does all the processing on your browser, so nothing is saved on our server unless you choose to save. Hightlight: This tool highlights the differences between the two Java files. It uses red color to highlight the deleted string and green color to highlight the added string. Also calculates the number of lines added and deleted.
๐ŸŒ
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 - Open this file in a browser. It will show the highlighted diff as shown below. You can take this & improve it further more on your own to achieve better diff tools. Here are few ideas to get you started. Currently if lines donโ€™t have 40% commonality, then we simply show them on separate lines, You can improve this to try to match it with next lines to see if it matches with other lines & align with that line instead.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ java โ€บ comparing files in java
Comparing Files in Java
February 1, 2018 - One of the good things is that if the same file is mapped into memory by two or more different processes, then the same memory area is used. That way, processes can even communicate with each other. The comparison application using memory-mapped files is the following: package packt.java9.network.niodemo; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class MapCompare { public static void main(String[] args) throws IOException { long start = System.nanoTime(); FileChannel ch1 = new RandomAccessFile("sample.t
Top answer
1 of 4
9

The below code will serve your purpose irrespective of the content of the file.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

    public class Test {
        public Test(){
            System.out.println("Test.Test()");
        }

        public static void main(String[] args) throws Exception {
            BufferedReader br1 = null;
            BufferedReader br2 = null;
            String sCurrentLine;
            List<String> list1 = new ArrayList<String>();
            List<String> list2 = new ArrayList<String>();
            br1 = new BufferedReader(new FileReader("test.txt"));
            br2 = new BufferedReader(new FileReader("test2.txt"));
            while ((sCurrentLine = br1.readLine()) != null) {
                list1.add(sCurrentLine);
            }
            while ((sCurrentLine = br2.readLine()) != null) {
                list2.add(sCurrentLine);
            }
            List<String> tmpList = new ArrayList<String>(list1);
            tmpList.removeAll(list2);
            System.out.println("content from test.txt which is not there in test2.txt");
            for(int i=0;i<tmpList.size();i++){
                System.out.println(tmpList.get(i)); //content from test.txt which is not there in test2.txt
            }

            System.out.println("content from test2.txt which is not there in test.txt");

            tmpList = list2;
            tmpList.removeAll(list1);
            for(int i=0;i<tmpList.size();i++){
                System.out.println(tmpList.get(i)); //content from test2.txt which is not there in test.txt
            }
        }
    }
2 of 4
2

The memory will be a problem as you need to load both files into the program. I am using HashSet to ignore duplicates.Try this:

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;

public class FileReader1 {
    public static void main(String args[]) {

        String filename = "abc.txt";
        String filename2 = "xyz.txt";
        HashSet <String> al = new HashSet<String>();
        HashSet <String> al1 = new HashSet<String>();
        HashSet <String> diff1 = new HashSet<String>();
        HashSet <String> diff2 = new HashSet<String>();
        String str = null;
        String str2 = null;
        try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            while ((str = in.readLine()) != null) {
                al.add(str);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            BufferedReader in = new BufferedReader(new FileReader(filename2));
            while ((str2 = in.readLine()) != null) {
                al1.add(str2);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (String str3 : al) {
            if (!al1.contains(str3)) {
                diff1.add(str3);
            }
        }
        for (String str5 : al1) {
            if (!al.contains(str5)) {
                diff2.add(str5);
            }
        }
        for (String str4 : diff1) {
            System.out.println("Removed Path: "+str4);
        }
        for (String str4 : diff2) {
            System.out.println("Added Path: "+str4);
        }


    }

}

Output:

Removed Path: E:\Users\Documents\hello\b.properties
Added Path: E:\Users\Documents\hello\h.properties
Added Path: E:\Users\Documents\hello\g.properties
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ how-to-compare-two-files-highlight-differences-java
How to Compare Two Files and Highlight Differences in Java? - CodingTechRoom
import java.nio.file.*; import java.io.IOException; public class FileComparator { public static void main(String[] args) throws IOException { String filePath1 = "path/to/first/file.txt"; String filePath2 = "path/to/second/file.txt"; compareFiles(filePath1, filePath2); } public static void compareFiles(String filePath1, String filePath2) throws IOException { List<String> file1Lines = Files.readAllLines(Paths.get(filePath1)); List<String> file2Lines = Files.readAllLines(Paths.get(filePath2)); for (int i = 0; i < Math.max(file1Lines.size(), file2Lines.size()); i++) { String line1 = (i < file1Lines.size()) ?
๐ŸŒ
Diffchecker
diffchecker.com
Compare text and find differences online or offline - Diffchecker
Compare text, files, and code (e.g. json, xml) to find differences with Diffchecker online for free! Use our desktop app for private, offline diffs.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ comparing-path-of-two-files-in-java
Comparing Path of Two Files in Java - GeeksforGeeks
October 6, 2022 - // Comparing path of two files in Java import java.io.File; public class GFG { public static void main(String[] args) { File file1 = new File("/home/mayur/GFG.java"); File file2 = new File("/home/mayur/file.txt"); File file3 = new File("/home/mayur/GFG.java"); // Path comparison if (file1.compareTo(file2) == 0) { System.out.println( "paths of file1 and file2 are same"); } else { System.out.println( "Paths of file1 and file2 are not same"); } // Path comparison if (file1.compareTo(file3) == 0) { System.out.println( "paths of file1 and file3 are same"); } else { System.out.println( "Paths of file1 and file3 are not same"); } } }
๐ŸŒ
w3resource
w3resource.com โ€บ java-exercises โ€บ io โ€บ java-io-exercise-6.php
Java - Compare two files lexicographically
Write a Java program to compare two files lexicographically by reading them as streams of bytes. Write a Java program to sort two files based on their contentโ€™s lexicographic order and output the comparison result. Write a Java program to compare files lexicographically using a custom comparator that ignores case differences. Write a Java program to compare two text files line by line lexicographically and report the first mismatch.