Scala: InputStream to Array[Byte]

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

    How about buffered version of solution based on streams plus ByteArraOutputStream to minimize boilerplate around final array growing?

    val EOF: Int = -1
    
    def readBytes(is: InputStream, bufferSize: Int): Array[Byte] = {
      val buf = Array.ofDim[Byte](bufferSize)
      val out = new ByteArrayOutputStream(bufferSize)
    
      Stream.continually(is.read(buf)) takeWhile { _ != EOF } foreach { n =>
        out.write(buf, 0, n)
      }
    
      out.toByteArray
    }
    

提交回复
热议问题