Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-conversion Convert InputStream to ByteArray

Related Tutorials


 
 

Share on Google+Share on Google+

Convert InputStream to ByteArray

Advertisement
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:

import java.io.*;
public class InputstramToByteArray
{
public static void main(String args[])throws IOException
  {
  InputStream itStrm=new FileInputStream(
 
"InputstramToByteArray.java" );
  String str=itStrm.toString();
  byte[] b3=str.getBytes();
  for(int i=0;i<b3.length;i++)
  System.out.print(b3[i]+"\t");
  }
}

The output of the program is given below:

C:\rajesh\io>javac InputstramToByteArray.java

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.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: June 20, 2007

Related Tutorials

Discuss: Convert InputStream to ByteArray   View All Comments

Post your Comment


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

This only outputs binary version of java.io.FileInputStream@<instanceid>. You can't read stream using it's method toString().
DMCA.com