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
Here's an approach using scalaz-stream:
import scalaz.concurrent.Task
import scalaz.stream._
import scodec.bits.ByteVector
def allBytesR(is: InputStream): Process[Task, ByteVector] =
io.chunkR(is).evalMap(_(4096)).reduce(_ ++ _).lastOr(ByteVector.empty)
Source.fromInputStream(is).map(_.toByte).toArray
We can do it using google API ByteStreams
import com.google.common.io.ByteStreams
pass the stream to ByteStreams.toByteArray method for conversion
ByteStreams.toByteArray(stream)
def inputStreamToByteArray(is: InputStream): Array[Byte] = {
val buf = ListBuffer[Byte]()
var b = is.read()
while (b != -1) {
buf.append(b.byteValue)
b = is.read()
}
buf.toArray
}
import scala.tools.nsc.io.Streamable
Streamable.bytes(is)
Don't remember how recent that is: probably measured in days. Going back to 2.8, it's more like
new Streamable.Bytes { def inputStream() = is } toByteArray