且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-30 18:50:37

最简单的方法是新建一个ByteArrayOutputStream,将字节复制到那个,然后调用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();
}