Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java file hash for identifying identical files

Tags:

java

mysql

hash

I would like to get the hash of files (mostly video files) independent of external properties such as path and file name. I'll be needing to store hash in a database and compare file hash to find identical files.

like image 954
infMt Avatar asked Feb 25 '23 09:02

infMt


2 Answers

Have a look at the DigestInputStream class: http://docs.oracle.com/javase/7/docs/api/java/security/DigestInputStream.html

like image 184
Brigham Avatar answered Feb 26 '23 21:02

Brigham


public byte[] digestFile( File f ){
  try {
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
    FileInputStream fis = new FileInputStream( f );
    byte[] buffer = new byte[1024];
    int read = -1;
    while ((read = fis.read(buffer)) != -1) {
      messageDigest.digest(buffer, 0, read);
    }
    return messageDigest.digest();
  } catch (VariousExceptions e) {
    //handle
  }
}
like image 24
Clint Avatar answered Feb 26 '23 23:02

Clint