【发布时间】:2013-11-29 07:03:17
【问题描述】:
我想得到一个文件目录的 MD5 校验和,我已经得到了一个文件的算法,但是当我将它用于一个目录时它结果为 null。如何快速获得校验和。 以下是我的文件算法(从匿名 stackoverflower 编辑)。
public String fileToMD5(String filePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath); // Create an FileInputStream instance according to the filepath
byte[] buffer = new byte[1024]; // The buffer to read the file
MessageDigest digest = MessageDigest.getInstance("MD5"); // Get a MD5 instance
int numRead = 0; // Record how many bytes have been read
while (numRead != -1) {
numRead = inputStream.read(buffer);
if (numRead > 0)
digest.update(buffer, 0, numRead); // Update the digest
}
byte [] md5Bytes = digest.digest(); // Complete the hash computing
return convertHashToString(md5Bytes); // Call the function to convert to hex digits
} catch (Exception e) {
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close(); // Close the InputStream
} catch (Exception e) { }
}
}
}
我搜索了一些解决方法:
- 预购目录下的文件。
- 将目录压缩成.zip或.rar等存档文件,并校验和。
- 将目录下的所有内容放入一个流中,并校验和。
我想知道是否有一些方便的解决方案。提前谢谢你。
【问题讨论】: