Java-实现文件的MD5编码获取

POM配置

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

MD5编号获取方法

/**
 * 求一个字符串的md5值
 * @param target 字符串
 * @return md5 value
 */
public static String md5(String target) {
    return DigestUtils.md5Hex(target);
}

/**
 * 获取一个文件的md5值(可处理大文件)
 * @return md5 value
 */
public static String md5(File file) {
    FileInputStream fileInputStream = null;
    try {
        MessageDigest MD5 = MessageDigest.getInstance("MD5");
        fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int length;
        while ((length = fileInputStream.read(buffer)) != -1) {
            MD5.update(buffer, 0, length);
        }
        return new String(Hex.encodeHex(MD5.digest()));
    } catch (Exception e) {
        return null;
    } finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) { }
    }
}

调用示例

public static void main(String[] args) {
    String path = "C:\\Users\\TMS1000\\Desktop\\xxx.jar";
    System.err.println(md5("1237675673453@fdg%"));
    System.err.println(md5(new File(path)));
}
上一篇:Springboot-系统启动初始化


下一篇:Java-实现文件sha1编码获取