获取文件的md5签名

/**
 * 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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值