Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert InputStream to byte array in Java

How do I read an entire InputStream into a byte array?

like image 796
JGC Avatar asked Aug 12 '09 07:08

JGC


People also ask

How do you convert an InputStream to byte array in Java?

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.

How do you convert InputStream to ByteArrayOutputStream?

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.

How do you get bytes from input stream?

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() .


2 Answers

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.

like image 123
Rich Seller Avatar answered Sep 30 '22 10:09

Rich Seller


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(); 
like image 40
Adamski Avatar answered Sep 30 '22 09:09

Adamski