Java怎么实现大文件切片多线程MD5计算呢?
最近在做文件的校验,一个1.5G的文件MD5计算结果耗时大概在5s左右,后续优化到下面的版本后,发现再怎么优化结果都是在3s左右。
现在在想能不能对文件进行切片,采取多线程分开计算的形式来计算MD5值。
我也试了几个版本,但是发现计算的结果和cmd计算的结果不一致。
certutil -hashfile <filepath> MD5
所以想提问一下:Java怎么实现大文件切片多线程MD5计算呢?
(CPU是i5-11600K)
下面是我写的单线程MD5计算方法
public static String getFileMD5 (File file) {
try {
Path path = file.toPath();
FileChannel fileChannel = FileChannel.open(path);
MessageDigest MD5 = MessageDigest.getInstance("MD5");
ByteBuffer buffer = ByteBuffer.allocate(8192);
while(fileChannel.read(buffer) != -1) {
buffer.flip();
MD5.update(buffer);
buffer.clear();
}
fileChannel.close();
return Hex.encodeHexString(MD5.digest());
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}