private static final int STREAM_BUFFER_LENGTH = 1024;
private static final String ALGORITHM_MD5 = "MD5";
public static String md5File(File file) {
if (null == file) {
return "";
}
String result = "";
try {
MessageDigest digest = MessageDigest.getInstance(ALGORITHM_MD5);
byte[] digests = updateDigest(digest, new FileInputStream(file)).digest();
BigInteger bi = new BigInteger(1, digests);
result = bi.toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static MessageDigest updateDigest(final MessageDigest digest, final InputStream data) throws IOException {
final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
while (read > -1) {
digest.update(buffer, 0, read);
read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
}
return digest;
}
原文:http://www.cnblogs.com/ivan-aldrich/p/4451304.html