我想得到一个文件目录的MD5校验和,我已经得到了一个文件的算法,但是当我将它用于一个目录时,它的结果为null。我怎样才能快速得到支票和。下面是我对一个文件(从匿名堆栈花中编辑)的协商。
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) { }
}
}
}我找到了一些解决办法:
我想知道是否提前有方便的solutions.Thank您。
发布于 2013-12-18 00:00:40
我只是这样做的,但我这样做的一个目录,我知道将是平坦的(没有子目录)
这会影响到,如果任何文件要更改,这个“目录”md5也会更改。
我知道还有其他的方法,包括你提到的方法(比如拉链),但这是我选择的路线。
编辑:我必须得到一个文件夹,它是子文件夹,md5,这就是我如何实现的。
注意:我使用了谷歌的番石榴库作为散列
注意:如果目录中的文件顺序改变了,那么我的代码的编写方式就会改变。
public static String generateMD5(String dir)
{
File[] files = new File(dir).listFiles();
return Hashing.md5().hashString(expandFiles(files, ""), Charsets.UTF_8).toString();
}
/* Recursive folder expansion */
public static String expandFiles(File[] dirFiles, String md5in)
{
String md5out = md5in;
for(File file : dirFiles)
{
if(file.isHidden()) //For my uses, I wanted to skip any hidden files (.DS_Store was being a problem on a mac)
{
System.out.println("We have skipped this hidden file: " + file.getName());
}
else if (file.isDirectory())
{
System.out.println("We are entering a directory recursively: " + file.getName());
md5out += Hashing.md5().hashString(expandFiles(file.listFiles(), md5out), Charsets.UTF_8).toString(); //Recursive call, we have found a subdirectory.
System.out.println("We have gotten the md5 of " + file.getName() + " It is " + md5out);
}
else //We found a file
{
HashCode md5 = null;
try
{
md5 = Files.hash(file, Hashing.md5());
}
catch (IOException e)
{
e.printStackTrace();
}
md5out += md5.toString();
System.out.println("We have just gotten the md5 of a specific file: " + file.getName() + ". This file has the md5 of " + md5out);
}
}
return md5out;https://stackoverflow.com/questions/20280112
复制相似问题