Java file hash to identify identical files

I would like to get a hash of files (mainly video files) regardless of external properties such as path and file name. I will need to store the hash in the database and compare the hash of the file to find identical files.

+4
source share
3 answers
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 } } 
+2
source
+5
source

Depending on what you need, you can do this quite easily using the Guava Files and ByteStreams classes:

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

All Articles