I am looking to use java or groovy to get the md5 checksum of a complete directory.
I have to copy directories for source to target, checksum source and target, and after delete source directories.
I find this script for files, but how to do the same thing with directories ?
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')
}
Is there a better approach ?
I made a function to calculate MD5 checksum on Directory :
First, I'm using FastMD5: http://www.twmacinta.com/myjava/fast_md5.php
Here is my code :
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
}