Convert InputStream to byte array in Java

In this post, we will discuss how to convert InputStream to byte array in Java.


 

1. ByteArrayOutputStream

The idea is to read each byte from the specified InputStream and write it to a ByteArrayOutputStream, then call toByteArray() to get the current contents of this output stream, as a byte array. Since number of bytes to be read is unknown, we have allocated the buffer of size 1024.

 

Download   Run Code

Output:

Techie Delight

 

2. Guava

We can use ByteStreams class from Guava, whose toByteArray() method reads all bytes from an input stream into a byte array.

 

Download   Run Code

Output:

Techie Delight

 

3. Apache Commons IO

Similar to Guava, Apache Commons IO has IOUtils class whose toByteArray() method returns the contents of an InputStream as a byte array.

 

Download

Output:

Techie Delight

 

4. sun.misc.IOUtils

We can also use sun.misc.IOUtils that is one of Sun’s proprietary Java classes. We should avoid their use as it is not guaranteed to work on all Java-compatible platforms or even in future versions on the same platform.

 

Download   Run Code

Output:

Techie Delight

 

5. Java 9

In Java 9, we can do something like:

 

or use ByteArrayOutputStream.transferTo() method:

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
Notify of