计算文件MD5


文件的MD5摘要一般用来表示文件的唯一识别码。本文提供一种生成文件MD5摘要的代码。

@Nullable
public static String getFileMD5(String filePath) {
    FileInputStream in = null;
    try {
        FileInputStream in = new FileInputStream(new File(filePath));
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[2048];
        int length;
        while ((length = in.read(buffer)) != -1) {
            md.update(buffer, 0, length);
        }
        byte[] b = md.digest();
        return byteToHexString(b);
    } catch (Exception ex) {
        Logger.e(TAG, ex);
        return null;
    } finally {
        if(in != null){
            in.Close();
        }
    }
}

在生成MD5字符串时,使用了BYTES -> HEX 的算法:

/**
* 把byte[]数组转换成十六进制字符串表示形式
* @param tmp 要转换的byte[]
* @return 十六进制字符串表示形式
*/
public static String byteToHexString(byte[] tmp) {
    char[] str = new char[(16 << 1)];
    int k = 0;
    for (int i = 0; i < 16; i++) {
        byte byte0 = tmp[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
    }
    return new String(str);
}
相关标签

扫一扫

在手机上阅读