How to convert InputStream to byte array in Java?


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

Thanxx in advanced!!



You will be able to convert the input string to byte array in Java. To perform this, you will need to read each byte from your InputStream and write the same into a ByteArrayOutputStream. Once done, you can retrieve the underlying byte array by calling the method toByteArray(). Let's take a sample example which is represented below. 

InputStream is = ... 

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int kRead;

byte[] data = new byte[16384];

while ((kRead =, 0, data.length)) != -1) 


  buffer.write(data, 0, kRead);


return buffer.toByteArray();


If you want to unleash your potential in this competitive field, please visit the Java course page for more information, where you can find the Java tutorials and Java frequently asked interview questions and answers as well.


This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.