Groovy web console

subscribe to the feed Subscribe
to this
site

MD5 Checksum for a File with a meta method

Published 10 years ago by Tim Yates with tags InputStream metaClass md5 hash File
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
InputStream.metaClass.eachByte = { int len, Closure c ->
  int read = 0
  byte[] buffer = new byte[ len ]
  while( ( read = delegate.read( buffer ) ) > 0 ) {
    c( buffer, read )
  }
}

File.metaClass.md5 = { ->
  def digest = java.security.MessageDigest.getInstance("MD5")
  delegate.withInputStream(){ is ->
    is.eachByte( 8192 ) { buffer, bytesRead ->
      digest.update( buffer, 0, bytesRead )
    }
  }
  new BigInteger( 1, digest.digest() ).toString( 16 ).padLeft( 32, '0' )
}

// Execute this using: new File( 'testfile.txt' ).md5()