JAVA获取文件MD5校验值
JAVA获取文件MD5校验值 JAVA字节数组转16进制字符串
/**
* 获取文件MD5
*
* @param path
* @return
*/
public static String getFileMD5(String path) {
/**
* if use BigInteger
* real 00667580b5ea2559d5a9ea86aebaceed
* but 667580b5ea2559d5a9ea86aebacaeed
*/
// BigInteger bi = null;
String strMd5 = null;
try {
byte[] buffer = new byte[8192];
int len = 0;
MessageDigest md = MessageDigest.getInstance("MD5");
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
while ((len = fis.read(buffer)) != -1) {
md.update(buffer, 0, len);
}
fis.close();
byte[] b = md.digest();
// bi = new BigInteger(1, b);
strMd5 = bytesToHexStr(b);
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
Log.e("MyDigestUtils", e.getMessage());
} catch (IOException e) {
// e.printStackTrace();
Log.e("MyDigestUtils", e.getMessage());
}
// return bi == null ? null : bi.toString(16);
return strMd5;
}
/**
* 字节数组转十六进制字符串
* @param b 字节数组
* @return 十六进制字符串
*/
public static String bytesToHexStr(byte[] b) {
StringBuilder strBuilder = new StringBuilder();
String strTemp = "";
for (int n = 0; n < b.length; ++n) {
strTemp = (Integer.toHexString(b[n] & 0XFF));
if (strTemp.length() == 1) {
strBuilder.append("0").append(strTemp);
} else {
strBuilder.append(strTemp);
}
}
return strBuilder.toString();
}