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()
Create a ByteArrayInputStream ByteArrayInputStream package first. Once we import the package, here is how we can create an input stream. // Creates a ByteArrayInputStream that reads entire array ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);
read(byte[] b) method reads b. length number of bytes from the input stream to the buffer array b. The bytes read is returned as integer.
How about:
Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
Update: use LazyList instead of Stream
(since Stream
is deprecated in Scala 3)
LazyList.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With