With Scala, what is the best way to read from an InputStream to a bytearray?
I can see that you can convert an InputStream to char array
Source.fromInput
Just removed bottleneck in our server code by replacing
Stream.continually(request.getInputStream.read()).takeWhile(_ != -1).map(_.toByte).toArray
with
org.apache.commons.io.IOUtils.toByteArray(request.getInputStream)
Or in pure Scala:
def bytes(in: InputStream, initSize: Int = 8192): Array[Byte] = {
var buf = new Array[Byte](initSize)
val step = initSize
var pos, n = 0
while ({
if (pos + step > buf.length) buf = util.Arrays.copyOf(buf, buf.length << 1)
n = in.read(buf, pos, step)
n != -1
}) pos += n
if (pos != buf.length) buf = util.Arrays.copyOf(buf, pos)
buf
}
Do not forget to close an opened input stream in any case:
val in = request.getInputStream
try bytes(in) finally in.close()