Getting a File's MD5 Checksum in Java Getting a File's MD5 Checksum in Java java java

Getting a File's MD5 Checksum in Java


There's an input stream decorator, java.security.DigestInputStream, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.

MessageDigest md = MessageDigest.getInstance("MD5");try (InputStream is = Files.newInputStream(Paths.get("file.txt"));     DigestInputStream dis = new DigestInputStream(is, md)) {  /* Read decorated stream (dis) to EOF as normal... */}byte[] digest = md.digest();


Use DigestUtils from Apache Commons Codec library:

try (InputStream is = Files.newInputStream(Paths.get("file.zip"))) {    String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);}


There's an example at Real's Java-How-to using the MessageDigest class.

Check that page for examples using CRC32 and SHA-1 as well.

import java.io.*;import java.security.MessageDigest;public class MD5Checksum {   public static byte[] createChecksum(String filename) throws Exception {       InputStream fis =  new FileInputStream(filename);       byte[] buffer = new byte[1024];       MessageDigest complete = MessageDigest.getInstance("MD5");       int numRead;       do {           numRead = fis.read(buffer);           if (numRead > 0) {               complete.update(buffer, 0, numRead);           }       } while (numRead != -1);       fis.close();       return complete.digest();   }   // see this How-to for a faster way to convert   // a byte array to a HEX string   public static String getMD5Checksum(String filename) throws Exception {       byte[] b = createChecksum(filename);       String result = "";       for (int i=0; i < b.length; i++) {           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );       }       return result;   }   public static void main(String args[]) {       try {           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));           // output :           //  0bb2827c5eacf570b6064e24e0e6653b           // ref :           //  http://www.apache.org/dist/           //          tomcat/tomcat-5/v5.5.17/bin           //              /apache-tomcat-5.5.17.exe.MD5           //  0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe       }       catch (Exception e) {           e.printStackTrace();       }   }}