Home Java Java-conversion Convert Inputstream to ByteArrayInputStream
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Convert Inputstream to ByteArrayInputStream

Advertisement
In this example we are going to convert InputStream to ByteArrayInputStream.

Convert Inputstream to ByteArrayInputStream

     

In this example we are going to convert InputStream to ByteArrayInputStream. 

To do so first read the file as input stream  using  FileInputStream. Then convert this input stream into string and then string into byte by using the toString() and getBytes() methods respectively. Pass the reference of the byte array into a ByteArrayInputStream class object. This makes the conversion of the byte array into the ByteArrayInputStream. Finally we are printing this ByteArrayInputStream.


The code of the program is given below:

import java.io.*;
public class InputStreamToByteArrayInputStream
{
  public static void main(String args[])
  {
  try
  {
  InputStream inputStream= new FileInputStream
(
"InputStreamToByteArrayInputStream.java");
  byte currentXMLBytes[] = inputStream.toString().getBytes();
  ByteArrayInputStream byteArrayInputStream = new 
ByteArrayInputStream
(currentXMLBytes);
  while(byteArrayInputStream.read()!=-1)
  System.out.println(byteArrayInputStream.read());
  }
  catch (IOException e){}
  }
}

The output of the program is given below:

C:\rajesh\io>javac InputStreamToByteArrayInputStream.java

C:\rajesh\io>java InputStreamToByteArrayInputStream
97
97
105
46
105
101
110
117
83
114
97
64
101
53
53.......

Download this example.

Advertisement

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 21, 2007

Related Tutorials

Ask Questions?    Discuss: Convert Inputstream to ByteArrayInputStream   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Geri
May 24, 2011
No, never ever...

...does this piece of code do what it's intended for: First, <code>InputStream.toString()</code> (which is inherited from <code>Object</code>!) returns something like "<code>java.io.FileInputStream@23fc4bec</code>", NOT the content of the underlying file. Calling read twice in the loop reads just every second byte, so the output really means: <code> 97 - a 97 - a 105 - i 46 - . 105 - i 101 - e 110 - n 117 - u 83 - S 114 - r 97 - a 64 - @ 51 - 3 99 - c 98 - b 99 - c</code> Compare this with the output of <code>.toString()</code> and recognize... That's how <code>read()</code> is used: int b; while (( b = stream.read()) != -1) { // ... do something with b ... }
DMCA.com