Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: InputStream to Array[Byte]

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() 
like image 847
rahul Avatar asked Feb 05 '11 05:02

rahul


People also ask

How do you create an input stream byte array?

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);

Which of the following methods reads r length bytes from the input stream into an array?

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.


1 Answers

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 
like image 144
Eastsun Avatar answered Sep 21 '22 15:09

Eastsun