在Java中将二进制输入流读入单个字节数组 [英] Reading a binary input stream into a single byte array in Java
问题描述
文档表示不应使用 available()
方法来确定 InputStream
的大小。如何将 InputStream
的全部内容读入字节数组?
The documentation says that one should not use available()
method to determine the size of an InputStream
. How can I read the whole content of an InputStream
into a byte array?
InputStream in; //assuming already present
byte[] data = new byte[in.available()];
in.read(data);//now data is filled with the whole content of the InputStream
我可以多次读入固定大小的缓冲区,但是,我必须将读取的数据合并为单个字节数组,这对我来说是一个问题。
I could read multiple times into a buffer of a fixed size, but then, I will have to combine the data I read into a single byte array, which is a problem for me.
推荐答案
最简单的方法IMO是使用番石榴及其 ByteStreams
class:
The simplest approach IMO is to use Guava and its ByteStreams
class:
byte[] bytes = ByteStreams.toByteArray(in);
或者文件:
byte[] bytes = Files.toByteArray(file);
或者(如果你不想使用Guava),你可以创建 ByteArrayOutputStream
,并重复读入一个字节数组并写入 ByteArrayOutputStream
(让它处理大小调整),然后调用 ByteArrayOutputStream.toByteArray()
。
Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream
, and repeatedly read into a byte array and write into the ByteArrayOutputStream
(letting that handle resizing), then call ByteArrayOutputStream.toByteArray()
.
请注意,无论您是否知道输入的长度,这种方法都有效 - 当然,假设您有足够的内存。
Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.
这篇关于在Java中将二进制输入流读入单个字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!