美文网首页
获取文件Md5,Md5Utils

获取文件Md5,Md5Utils

作者: wenju | 来源:发表于2021-03-02 11:43 被阅读0次
public final class Md5Utils {

    private Md5Utils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 获取文件的MD5值
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!FileUtils.isFileExists(file)) {
            return "";
        }
        InputStream fis = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            fis = FileUtils.getFileInputStream(file);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            return bytes2Hex(digest.digest());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtils.closeIOQuietly(fis);
        }
        return "";
    }

    /**
     * 一个byte转为2个hex字符
     *
     * @param src byte数组
     * @return 16进制大写字符串
     */
    private static String bytes2Hex(byte[] src) {
        char[] res = new char[src.length << 1];
        final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        for (int i = 0, j = 0; i < src.length; i++) {
            res[j++] = hexDigits[src[i] >>> 4 & 0x0F];
            res[j++] = hexDigits[src[i] & 0x0F];
        }
        return new String(res);
    }

}

相关文章

网友评论

      本文标题:获取文件Md5,Md5Utils

      本文链接:https://www.haomeiwen.com/subject/qfvtqltx.html