Convert InputStream to byte array in Java

如何将整个InputStream读入字节数组?


You can use Apache Commons IO to handle this and similar tasks.

The IOUtils type has a static method to read an InputStream and return a byte[] .

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

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.


You need to read each byte from your InputStream and write it to a ByteArrayOutputStream . You can then retrieve the underlying byte array by calling toByteArray() ; eg

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

buffer.flush();

return buffer.toByteArray();

Finally, after twenty years, there's a simple solution without the need for a 3rd party library, thanks to Java 9:

InputStream is;
…
byte[] array = is.readAllBytes();

Note also the convenience methods readNBytes(byte[] b, int off, int len) and transferTo(OutputStream) addressing recurring needs.

链接地址: http://www.djcxy.com/p/34888.html

上一篇: xml输出中的nolatin字符

下一篇: 用Java将InputStream转换为字节数组