Scala: InputStream to Array[Byte]

后端 未结 11 1038
臣服心动
臣服心动 2021-02-02 06:01

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         


        
11条回答
  •  青春惊慌失措
    2021-02-02 06:47

    In a similar vein to Eastsun's answer... I started this as a comment, but it ended up getting just a bit to long!

    I'd caution against using Stream, if holding a reference to the head element then streams can easily consume a lot of memory.

    Given that you're only going to read in the file once, then Iterator is a much better choice:

    def inputStreamToByteArray(is: InputStream): Array[Byte] =
      Iterator continually is.read takeWhile (-1 !=) map (_.toByte) toArray
    

提交回复
热议问题