Scala:InputStream to Array [Byte]

rah*_*hul 39 scala bytearray inputstream

使用Scala,从InputStream读取到bytearray的最佳方法是什么?

我可以看到你可以将InputStream转换为char数组

Source.fromInputStream(is).toArray()
Run Code Online (Sandbox Code Playgroud)

Eas*_*sun 45

怎么样:

Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
Run Code Online (Sandbox Code Playgroud)

  • 这不会创建一个巨大的链表,然后将其转换为数组吗?在时间或记忆方面看起来效率不高. (11认同)

And*_*yuk 43

刚刚通过替换删除了我们的服务器代码中的瓶颈

Stream.continually(request.getInputStream.read()).takeWhile(_ != -1).map(_.toByte).toArray
Run Code Online (Sandbox Code Playgroud)

org.apache.commons.io.IOUtils.toByteArray(request.getInputStream)
Run Code Online (Sandbox Code Playgroud)


Kev*_*ght 18

与Eastsun的答案类似的是......我把它作为一个评论开始了,但它最终变得有点长!

我要小心不要使用Stream,如果持有对head元素的引用,那么stream很容易消耗大量内存.

鉴于您只需要在文件中读取一次,那么这Iterator是一个更好的选择:

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


psp*_*psp 13

import scala.tools.nsc.io.Streamable
Streamable.bytes(is)
Run Code Online (Sandbox Code Playgroud)

不记得最近的情况:可能以天为单位.回到2.8,更像是

new Streamable.Bytes { def inputStream() = is } toByteArray
Run Code Online (Sandbox Code Playgroud)

  • 它现在似乎已经转移到更标准的 `scala.reflect.io` 包。 (2认同)

Wil*_*ger 11

使用Scala IO,这应该工作:

def inputStreamToByteArray(is: InputStream): Array[Byte] = 
   Resource.fromInputStream(in).byteArray
Run Code Online (Sandbox Code Playgroud)


pat*_*rit 5

使用更好的文件,您可以轻松完成is.bytes

  • better.files 应该位于标准库中。好多了。另外,如果您想要“Array[Byte]”,则需要使用“is.byteArray”。 (3认同)