Scala: InputStream to Array[Byte]

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

    Just removed bottleneck in our server code by replacing

    Stream.continually(request.getInputStream.read()).takeWhile(_ != -1).map(_.toByte).toArray
    

    with

    org.apache.commons.io.IOUtils.toByteArray(request.getInputStream)
    

    Or in pure Scala:

    def bytes(in: InputStream, initSize: Int = 8192): Array[Byte] = {
      var buf = new Array[Byte](initSize)
      val step = initSize
      var pos, n = 0
      while ({
        if (pos + step > buf.length) buf = util.Arrays.copyOf(buf, buf.length << 1)
        n = in.read(buf, pos, step)
        n != -1
      }) pos += n
      if (pos != buf.length) buf = util.Arrays.copyOf(buf, pos)
      buf
    }
    

    Do not forget to close an opened input stream in any case:

    val in = request.getInputStream
    try bytes(in) finally in.close()
    

提交回复
热议问题