Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created May 15, 2014 20:54
Show Gist options
  • Save bdkosher/fda455eaf102310f4d8c to your computer and use it in GitHub Desktop.
Save bdkosher/fda455eaf102310f4d8c to your computer and use it in GitHub Desktop.
A friendlier version of InputStream's eachByte method that provides you a correctly-sized byte[] for the last invokation of the provided closure.
InputStream.metaClass.eachChunk << { int preferredChunkSize, Closure closure ->
delegate.eachByte(preferredChunkSize) { buffer, bytesRead ->
if (bytesRead == preferredChunkSize) {
closure(buffer)
} else if (bytesRead > 0) {
byte[] data = new byte[bytesRead]
System.arraycopy(buffer, 0, data, 0, bytesRead)
closure(data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment