Scala: InputStream to Array[Byte]

rahul picture rahul · Feb 5, 2011 · Viewed 35k times · Source

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.fromInputStream(is).toArray()

Answer

Eastsun picture Eastsun · Feb 5, 2011

How about:

Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray

Update: Use LazyList instead of Stream (since 2.13.x deprecated)

LazyList.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray