Scala: InputStream to Array[Byte]

后端 未结 11 843
臣服心动
臣服心动 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:52

    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)
    
    0 讨论(0)
  • 2021-02-02 06:53

    Source.fromInputStream(is).map(_.toByte).toArray

    0 讨论(0)
  • 2021-02-02 06:56

    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)
    
    0 讨论(0)
  • 2021-02-02 06:57
    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
    }
    
    0 讨论(0)
  • 2021-02-02 07:06
    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
    
    0 讨论(0)
提交回复
热议问题