Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Generate MD5 hash of a file while being as Groovy as possible.
def generateMD5( File file ) {
def digest ="MD5")
file.eachByte( 4096 ) { buffer, length ->
digest.update( buffer, 0, length )
new BigInteger(1, digest.digest()).toString(16).padLeft(32, '0')

The hex encoding can also be done like this:

digest.digest().encodeHex() as String

Vampire commented Dec 11, 2015

I'd say

def generateMD5(File file) {
   file.withInputStream {
      new DigestInputStream(it, MessageDigest.getInstance('MD5')).withStream {
         it.eachByte {}
         it.messageDigest.digest().encodeHex() as String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment