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.

|