在Java中,如何将InputStream转换为字节数组(byte[])?

发布于 2024-08-19 14:44:05 字数 135 浏览 4 评论 0原文

我的背景是 .net,我对 Java 还很陌生。我正在为我们公司的 java 团队做一些工作,架构师需要我实现一个采用 InputStream (java.io) 对象的方法。为了实现该方法的目的,我需要将其转换为字节数组。有没有简单的方法可以做到这一点?

My background is .net, I'm fairly new to Java. I'm doing some work for our company's java team and the architect needs me to implement a method that takes an InputStream (java.io) object. In order to fulfill the method's purpose I need to convert that into a byte array. Is there an easy way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟─花易冷 2024-08-26 14:44:05

最简单的方法是创建一个新的 ByteArrayOutputStream,将字节复制到其中,然后调用 toByteArray:

public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}

The simplest way is to create a new ByteArrayOutputStream, copy the bytes to that, and then call toByteArray:

public static byte[] readFully(InputStream input) throws IOException
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = input.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    return output.toByteArray();
}
爱*していゐ 2024-08-26 14:44:05

一种简单的方法是使用 org.apache.commons.io.IOUtils.toByteArray( inputStream ) ,请参阅 apache commons io

A simple way would be to use org.apache.commons.io.IOUtils.toByteArray( inputStream ), see apache commons io.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文