Calculate MD5 for File content - Android java.security

Android examples for java.security:MD5

Description

Calculate MD5 for File content

Demo Code

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

public class Main {
  private final static char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
      'F' };/* ww  w.  ja v a  2 s.co  m*/

  private static String toHexString(byte[] b) {
    StringBuilder str = new StringBuilder(b.length * 2);
    for (int i = 0; i < b.length; i++) {
      str.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
      str.append(HEX_DIGITS[b[i] & 0x0f]);
    }
    return str.toString();
  }

  public static String checkFilemd5(String filename) {
    if (filename == null) {
      return "";
    }
    InputStream fis = null;
    byte[] buffer = new byte[1024];
    int numRead = 0;
    MessageDigest md5;
    try {
      fis = new FileInputStream(filename);
      md5 = MessageDigest.getInstance("MD5");
      while ((numRead = fis.read(buffer)) > 0) {
        md5.update(buffer, 0, numRead);
      }
      return toHexString(md5.digest());
    } catch (Exception e) {
      System.out.println("error");
      return null;
    } finally {
      try {
        if (fis != null)
          fis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

}

Related Tutorials