Skip to content

Instantly share code, notes, and snippets.

@takezoe
Created November 17, 2011 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takezoe/1372537 to your computer and use it in GitHub Desktop.
Save takezoe/1372537 to your computer and use it in GitHub Desktop.
read bytes from java.io.InputStream and process them by closure
processInputStream(new java.io.FileInputStream("test.jpg"), 8 * 1024){ bytes =>
...
}
/**
* Invokes the given function for each read bytes with specified size from java.io.InputStream.
*/
@tailrec
def processInputStream(in: java.io.InputStream, bufferSize: Int)(func: Array[Byte] => Unit): Unit = {
val buffer = new Array[Byte](bufferSize)
in.read(buffer) match {
case -1 =>
case len => func(buffer.slice(0, len)); processInputStream(in, bufferSize)(func)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment