4

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.

1
  • 1
    You can make a hash function depend on anything you like, including 'external properties' or not. What is it about writing such a function that you don't understand? Commented Apr 29, 2011 at 15:47

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

2
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
  }
}

Comments

1

Depending on what you need, you can do this pretty easily using Guava's Files and ByteStreams classes:

byte[] digest = Files.getDigest(file, MessageDigest.getInstance("SHA"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.