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.

|