安卓获取文件md5码
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMd5Util {
/**
* 计算文件MD5
* @param file 文件
* @return 小写32位md5字符串,文件不存在返回null
*/
public static String getFileMD5(File file) {
if (!file.exists() || file.isDirectory()) {
return null;
}
MessageDigest md5Digest;
try {
md5Digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] buffer = new byte[8192];
int len;
while ((len = bis.read(buffer)) != -1) {
md5Digest.update(buffer, 0, len);
}
byte[] digestBytes = md5Digest.digest();
return bytesToHex(digestBytes);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 字节数组转小写16进制字符串
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* 校验文件MD5是否等于指定值
* @param file 文件
* @param expectedMd5 预期md5(大小写不敏感)
* @return true=一致;false=不一致/文件异常
*/
public static boolean verifyFileMd5(File file, String expectedMd5) {
String realMd5 = getFileMD5(file);
if (realMd5 == null || expectedMd5 == null) {
return false;
}
return realMd5.equalsIgnoreCase(expectedMd5);
}
}
浙公网安备 33010602011771号