Skip to content

Instantly share code, notes, and snippets.

@pauca
Created June 14, 2019 09:18
Show Gist options
  • Save pauca/bd0dc35905528c947b5cc06d956fd0a4 to your computer and use it in GitHub Desktop.
Save pauca/bd0dc35905528c947b5cc06d956fd0a4 to your computer and use it in GitHub Desktop.
get md5sum from path with scala
//inspired by http://www.michaelpollmeier.com/2018/12/10/checksum-files-scala
import java.io.File
import java.nio.file.Files
import java.security.{DigestInputStream, MessageDigest}
import scala.collection.JavaConverters._
def md5(roots: File*): String = {
val md = MessageDigest.getInstance("MD5")
roots.foreach { root =>
Files.walk(root.toPath).iterator().asScala.filter( x => ! x.toFile.isDirectory).foreach { path =>
val dis = new DigestInputStream(Files.newInputStream(path), md)
// fully consume the inputstream
while (dis.available > 0) {
dis.read
}
dis.close
}
}
md.digest.map(b => String.format("%02x", Byte.box(b))).mkString
}
// usage:
//md5(new File("somepath"))
// testing
import java.io._
import sys.process._
val pw = new PrintWriter(new File("hello.txt" ))
pw.write("Hello, world")
pw.close
"md5sum hello.txt".!!.takeWhile( _ != ' ' ) == md5(new File("hello.txt"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment