-
-
Save mcquinne/2655782 to your computer and use it in GitHub Desktop.
Generate MD5 hash of a file while being as Groovy as possible.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generateMD5( File file ) { | |
def digest = java.security.MessageDigest.getInstance("MD5") | |
file.eachByte( 4096 ) { buffer, length -> | |
digest.update( buffer, 0, length ) | |
} | |
new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0') | |
} |
I'd say
def generateMD5(File file) {
file.withInputStream {
new DigestInputStream(it, MessageDigest.getInstance('MD5')).withStream {
it.eachByte {}
it.messageDigest.digest().encodeHex() as String
}
}
}
import java.nio.file.Path
Path.metaClass.getMd5 << { ->
def digest = java.security.MessageDigest.getInstance("MD5")
delegate.withInputStream { stream ->
stream.eachByte 4096, { buffer, length ->
digest.update( buffer, 0, length )
}
}
digest.digest().encodeHex() as String
}
File.metaClass.getMd5 << { -> delegate.toPath().md5 }
def f = new File('/Users/pwg947/incoming_transactions.tsv')
f.md5
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The hex encoding can also be done like this: