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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2163644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:17:54  来源:igfitidea点击:

In Java, how can I convert an InputStream into a byte array (byte[])?

javatype-conversioninputstream

提问by Lee Warner

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?

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

采纳答案by Jon Skeet

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

最简单的方法是创建一个 new 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();
}

回答by tangens

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

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