Fab*_*ier 5 java directory groovy checksum md5
我希望使用java或groovy来获取完整目录的md5校验和.
我必须将源目录,目标,校验和源和目标以及删除源目录后的目录复制.
我发现这个文件的脚本,但如何与目录做同样的事情?
import java.security.MessageDigest
def generateMD5(final file) {
MessageDigest digest = MessageDigest.getInstance("MD5")
file.withInputStream(){ is ->
byte[] buffer = new byte[8192]
int read = 0
while( (read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
}
byte[] md5sum = digest.digest()
BigInteger bigInt = new BigInteger(1, md5sum)
return bigInt.toString(16).padLeft(32, '0')
}
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?
我有相同的要求,并选择我的'目录哈希'作为目录中所有(非目录)文件的连接流的MD5哈希.正如crozin在类似问题的评论中提到的那样,您可以使用SequenceInputStream它作为连接其他流的负载的流.我正在使用Apache Commons Codec进行MD5算法.
基本上,您通过目录树递归,将FileInputStream实例添加到Vector非目录文件.Vector然后方便地有elements()提供的方法Enumeration是SequenceInputStream通过需要循环.对于MD5算法,这只是一个InputStream.
一个问题是,每次哈希与相同输入相同时,您需要以相同顺序呈现的文件.该listFiles()方法File不保证排序,所以我按文件名排序.
我正在为SVN控制的文件做这个,并且想避免散列隐藏的SVN文件,所以我实现了一个标志以避免隐藏文件.
相关基本代码如下.(显然它可以'硬化'.)
import org.apache.commons.codec.digest.DigestUtils;
import java.io.*;
import java.util.*;
public String calcMD5HashForDir(File dirToHash, boolean includeHiddenFiles) {
assert (dirToHash.isDirectory());
Vector<FileInputStream> fileStreams = new Vector<FileInputStream>();
System.out.println("Found files for hashing:");
collectInputStreams(dirToHash, fileStreams, includeHiddenFiles);
SequenceInputStream seqStream =
new SequenceInputStream(fileStreams.elements());
try {
String md5Hash = DigestUtils.md5Hex(seqStream);
seqStream.close();
return md5Hash;
}
catch (IOException e) {
throw new RuntimeException("Error reading files to hash in "
+ dirToHash.getAbsolutePath(), e);
}
}
private void collectInputStreams(File dir,
List<FileInputStream> foundStreams,
boolean includeHiddenFiles) {
File[] fileList = dir.listFiles();
Arrays.sort(fileList, // Need in reproducible order
new Comparator<File>() {
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
});
for (File f : fileList) {
if (!includeHiddenFiles && f.getName().startsWith(".")) {
// Skip it
}
else if (f.isDirectory()) {
collectInputStreams(f, foundStreams, includeHiddenFiles);
}
else {
try {
System.out.println("\t" + f.getAbsolutePath());
foundStreams.add(new FileInputStream(f));
}
catch (FileNotFoundException e) {
throw new AssertionError(e.getMessage()
+ ": file should never not be found!");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我做了一个函数来计算 Directory 上的 MD5 校验和:
首先,我使用的是 FastMD5:http ://www.twmacinta.com/myjava/fast_md5.php
这是我的代码:
def MD5HashDirectory(String fileDir) {
MD5 md5 = new MD5();
new File(fileDir).eachFileRecurse{ file ->
if (file.isFile()) {
String hashFile = MD5.asHex(MD5.getHash(new File(file.path)));
md5.Update(hashFile, null);
}
}
String hashFolder = md5.asHex();
return hashFolder
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17871 次 |
| 最近记录: |