在Java中将InputStream转换为字节数组 [英] Convert InputStream to byte array in Java

查看:3552
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆