在Java中将InputStream转换为字节数组
问题描述:
如何将整个 InputStream
读入字节数组?
How do I read an entire InputStream
into a byte array?
答
您可以使用Apache Commons IO 来处理此类和类似任务。
You can use Apache Commons IO to handle this and similar tasks.
IOUtils
类型有一个静态方法来读取 InputStream
并返回一个 byte []
。
The IOUtils
type has a static method to read an InputStream
and return a byte[]
.
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
在内部创建 ByteArrayOutputStream
并复制字节到输出,然后调用 toByteArray()
。它通过复制4KiB块中的字节来处理大文件。
Internally this creates a ByteArrayOutputStream
and copies the bytes to the output, then calls toByteArray()
. It handles large files by copying the bytes in blocks of 4KiB.