Share on Google+Share on Google+

Convert InputStream to ByteArray

Here we will learn the conversion of an input stream into a byte array.

Convert InputStream to ByteArray


Here we will learn the conversion of an input stream into a byte array.

To convert the InputStream into a ByteArray first we read a file from the system by using FileInputStream. Since class InputStream is super class of the FileInputStream so we can store file into InputStream to take the file as input stream. To convert the input stream into string we use toString() method and then we use the method getBytes() to convert the string into byte array. Finally we display the string as output.

The code of the program is given below:

public class InputstramToByteArray
public static void main(String args[])throws IOException
  InputStream itStrm=new FileInputStream(
"" );
  String str=itStrm.toString();
  byte[] b3=str.getBytes();
  for(int i=0;i<b3.length;i++)

The output of the program is given below:


C:\rajesh\io>java InputstramToByteArray
106 97 118 97 46 105 111 46 70 105
108 101 73 110 112 117 116 83 116 114
101 97 109 64 51 101 50 53 97 53

Download this example.



Posted on: June 20, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Convert InputStream to ByteArray   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Ond?ej Sv?tlík
June 14, 2011
This doesn't read the stream

This only outputs binary version of<instanceid>. You can't read stream using it's method toString().