This post will discuss how to compare the contents of two files to determine whether they are equal in Java.

There are several ways to compare the contents of two files to determine equality in plain Java and using third-party libraries. These are discussed below in detail:

1. Using Apache Commons IO

Apache Commons IO’s FileUtils class has several utility methods for working with files. To compare the contents of two files, we can use its contentEquals(…) method, which returns true only if the content of both files are equal or they both don’t exist.

This method checks for the existence of both files, checks that both files are regular files and not a directory, compares the length of both files, or if they point to the same file, before resorting to the byte-by-byte comparison of the contents.

Download Code

2. Using Arrays.equals() method

In JDK, we can simply read the entire files into byte arrays and then compare both arrays for equality. To read all the bytes from a file into a byte array, we can use Files.readAllBytes() method, and byte arrays equality can be checked using Arrays.equals(), as demonstrated below:

Download Code

3. Using BufferedInputStream

The above approach is not recommended for large files as it might exhaust the heap memory. If the files are large, instead of reading the entire files into arrays, we should use BufferedReader and read the files chunk-by-chunk.

⮚ Read character-by-character using BufferedReader‘s read() method

Download Code

⮚ Read line-by-line using BufferedReader‘s readLine() method

Download Code

That’s all about comparing the contents of two files for determining equality in Java.