事情起因是因为这句话:
String md = DigestUtils.md5Hex(Files.newInputStream(Paths.get(filePath)));
这句话虽然返回了正确的md值,但是会锁住后续的文件操作。所以应该自己封装一个安全的函数使用try包裹住才好。
比方说改成这样:
java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileMD5Calculator {
public static String calculateMD5(String filePath) {
try (RandomAccessFile file = new RandomAccessFile(filePath, "r");
FileChannel channel = file.getChannel()) {
MessageDigest digest = MessageDigest.getInstance("MD5");
ByteBuffer buffer = ByteBuffer.allocate(8192); // 分配 8KB 的缓冲区
int bytesRead = 0;
while ((bytesRead = channel.read(buffer)) != -1) {
buffer.flip(); // 切换至读模式
digest.update(buffer);
buffer.clear(); // 清空缓冲区,为下一次读取做准备
}
byte[] hash = digest.digest();
return bytesToHex(hash);
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
public static void main(String[] args) {
String filePath = "your_file_path_here";
String md5 = calculateMD5(filePath);
System.out.println("MD5: " + md5);
}
}
虽然是个小问题吧。
文件处理时的经验提升!