How do I read an entire InputStream
into a byte array?
Example 1: Java Program to Convert InputStream to Byte ArrayreadAllBytes(); Here, the readAllBytes() method returns all the data from the stream and stores in the byte array. Note: We have used the Arrays. toString() method to convert all the entire array into a string.
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(); e.g. ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is. read(data, 0, data.
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() .
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()
:
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); } return buffer.toByteArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With