背景
对文件进行md5值作为摘要,作为其他地方下载文件时的一个校验。 本文不讨论MD5算法可能发生的碰撞。
具体实现
具体实现方法有很多种,这里以https://www.baeldung.com/java-md5 中一种最方便的示例为例子
public static String getDigest(String fullFilePath) throws Exception {
try (InputStream is = Files.newInputStream(Paths.get(fullFilePath))) {
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(is);
return md5;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
相比其他方法,这个直接传入文件的全路径(文件路径和文件全名),直接获得md5值, 省去打开文件读取文件内容的步骤。 简单直接。
如下这种直接使用google对应类库的也很方便
public String getMD5Checksum(String fullFilePath)
throws IOException {
HashCode hash = com.google.common.io.Files
.hash(new File(fullFilePath), Hashing.md5());
String myChecksum = hash.toString().toUpperCase();
return myChecksum;
}