/**
* Get the md5 for the file. call getMD5(FileInputStream is, int bufLen) inside.
*
* @param file
*/
public static String getMD5(final File file) {
if (file == null || !file.exists()) {
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
String md5 = getMD5(fin);
fin.close();
return md5;
} catch (Exception e) {
return null;
} finally {
try {
if (fin != null) {
fin.close();
}
} catch (IOException e) {
}
}
}
/**
* Get the md5 for inputStream.
* This method cost less memory. It read bufLen bytes from the FileInputStream once.
*
* @param is
*/
public final static String getMD5(final InputStream is) {
if (is == null) {
return null;
}
try {
BufferedInputStream bis = new BufferedInputStream(is);
MessageDigest md = MessageDigest.getInstance("MD5");
StringBuilder md5Str = new StringBuilder(32);
byte[] buf = new byte[ShareConstants.MD5_FILE_BUF_LENGTH];
int readCount;
while ((readCount = bis.read(buf)) != -1) {
md.update(buf, 0, readCount);
}
byte[] hashValue = md.digest();
for (int i = 0; i < hashValue.length; i++) {
md5Str.append(Integer.toString((hashValue[i] & 0xff) + 0x100, 16).substring(1));
}
return md5Str.toString();
} catch (Exception e) {
return null;
}
}