在 Java 中将 InputStream 转换为字节数组 [英] Convert InputStream to byte array in Java
本文介绍了在 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.
这篇关于在 Java 中将 InputStream 转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文