Java: How to check that 2 binary files are same?

There's always just reading byte by byte from each file and comparing them as you go. Md5 and Sha1 etc still have to read all the bytes so computing the hash is extra work that you don't have to do.

if (file1.length() != file2.length()) {
    return false;
}
    
 try( InputStream in1 = new BufferedInputStream(new FileInputStream(file1));
    InputStream in2 = new BufferedInputStream(new FileInputStream(file2));
 ) {

      int value1, value2;
      do {
           //since we're buffered, read() isn't expensive
           value1 = in1.read();
           value2 = in2.read();
           if(value1 != value2) {
               return false;
           }
      } while(value1 >= 0);
     
 // since we already checked that the file sizes are equal 
 // if we're here we reached the end of both files without a mismatch
 return true;
}

Are third-party libraries fair game? Guava has Files.equal(File, File). There's no real reason to bother with hashing if you don't have to; it can only be less efficient.

Tags:

Java