Scala:输入流到数组[字节]
使用 Scala,从 InputStream 读取字节数组的最佳方法是什么?
我可以看到您可以将 InputStream 转换为 char 数组
Source.fromInputStream(is).toArray()
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.fromInputStream(is).toArray()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
怎么样:
更新:使用 LazyList 而不是
Stream
(因为Stream
在 Scala 3 中已弃用)How about:
Update: use LazyList instead of
Stream
(sinceStream
is deprecated in Scala 3)Or来消除服务器代码中的瓶颈
刚刚通过在纯 Scala 中替换为
:
在任何情况下都不要忘记关闭打开的输入流:
Just removed bottleneck in our server code by replacing
with
Or in pure Scala:
Do not forget to close an opened input stream in any case:
与 Eastsun 的回答类似……我一开始是作为评论,但最终变得有点长了!
我警告不要使用 Stream,如果持有对 head 元素的引用,那么流很容易消耗大量内存。
鉴于您只会读取文件一次,那么
Iterator
是一个更好的选择: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:不记得那是多久以前的事:可能以天为单位。回到2.8,它更像是
Don't remember how recent that is: probably measured in days. Going back to 2.8, it's more like
使用 Scala IO,这应该可以工作:
With Scala IO, this should work:
使用 better-files,您可以简单地执行
is.bytes
With better-files, you can simply do
is.bytes
Source.fromInputStream(is).map(_.toByte).toArray
Source.fromInputStream(is).map(_.toByte).toArray
基于流和 ByteArraOutputStream 的解决方案的缓冲版本如何最大限度地减少最终数组增长的样板?
How about buffered version of solution based on streams plus ByteArraOutputStream to minimize boilerplate around final array growing?
这是使用 scalaz-stream 的方法:
Here's an approach using scalaz-stream:
从 JDK 9 开始:
Since JDK 9:
我们可以使用 Google API ByteStreams
将流传递给 ByteStreams.toByteArray 方法进行转换
We can do using Google API ByteStreams
pass the stream to ByteStreams.toByteArray method for conversion