How to convert input stream into byte array in java.

How to convert input stream into byte array in java.


Posted in : Core Java Posted on : October 21, 2010 at 12:57 PM Comments : [ 0 ]

Here, we will convert input stream into byte array in java.

How to convert input stream into byte array in java.

In this example, we will see how to convert input stream to bye array in java. First of all read the file as input stream using FileInputStream. Then convert this input stream into string by using the toString() and string into byte array by using getBytes() methods.

Code:
InputStreamToByteArray.java
package devmanuals.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class InputStreamToByteArray {
	public static void main(String[] args) throws IOException {
		String str = "TestFile.txt";
		FileInputStream inputStream = new FileInputStream(new File(str));

		String stringData = inputStream.toString();
		byte[] byteArray = stringData.getBytes();
		System.out.println("After conversion a input stream "
				+ "into byte array data in byte array.. ");
		for (int i = 0; i < byteArray.length; i++) {
			System.out.print(byteArray[i] + " ");
		}
	}
}
Output:
After conversion a input stream into byte array data in byte array..
106 97 118 97 46 105 111 46 70 105 108 101 73 110 112 117 116 83 116 114 101 97 109 64 49 57 56 50 49 102

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics