Java Compare Two File Byte By Byte

For comparing two files best way is to compare them byte by byte or we can do this by computing and comparing MD5 checksum of both files. For comparing file(s) byte by byte the method contentEquals of FileUtils class of Apache Commons IO Java library is best option as it has all checks and well tested code. Read here for comparing two text files line by line.

Library Information

Platform information

jdk1.8.0_60, Java 8, Eclipse

Used library Name: Commons IO

Maven Dependency Entry

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

Gradle Dependency Entry

compile \'commons-io:commons-io:2.4\'

Jar Download Location: Download Jar

Methods used: FileUtils provides method contentEquals to compare two text files byte by byte. This method checks to see if the two files are different lengths or if they point to the same file, before resorting to byte-by-byte comparison of the contents.. These methods have all required checks and exception handling. For any production grade Java application it is good to use this utility as it will save effort.

Example
package org.code4copy;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class CompareTwoBinaryFiles {
public static void main(String[] args) throws IOException {
File f1 = new File("C:\\example\\1.txt");
File f2 = new File("C:\\example\\2.txt");
boolean result = FileUtils.contentEquals(f1, f2);
if(!result){
System.out.println("Files content are not equal.");
}else{
System.out.println("Files content are equal.");
}
result = FileUtils.contentEquals(f1, f1);
if(!result){
System.out.println("Files content are not equal.");
}else{
System.out.println("Files content are equal.");
}
}
}

Output

Files content are not equal.
Files content are equal.

Download code from here

Leave a Reply

Your email address will not be published. Required fields are marked *