天天看点

获取文件md5 java,用Java获取文件的MD5校验和

获取文件md5 java,用Java获取文件的MD5校验和

I am looking to use Java to get the MD5 checksum of a file. I was really surprised but I haven't been able to find anything that shows how to get the MD5 checksum of a file.

How is it done?

解决方案

There's an input stream decorator, java.security.DigestInputStream, so that you can compute the digest while using the input stream as you normally would, instead of having to make an extra pass over the data.

MessageDigest md = MessageDigest.getInstance("MD5");

try (InputStream is = Files.newInputStream(Paths.get("file.txt"));

DigestInputStream dis = new DigestInputStream(is, md))

{

}

byte[] digest = md.digest();