|
How to convert InputStream to Byte Array
The following example shows reading the content from an InputStream as Byte Array.
|
package com.bethecoder.articles.basics.ins2bytea;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;
public class InputStream2ByteArrayTest {
/**
* @param args
*/
public static void main(String[] args) {
InputStream ins = InputStream2ByteArrayTest.class
.getClassLoader().getResourceAsStream("ABC.txt");
byte [] streamAsBytes = stream2Bytes(ins);
System.out.println(Arrays.toString(streamAsBytes));
System.out.println(new String(streamAsBytes));
}
public static byte[] stream2Bytes(InputStream ins) {
byte [] availableBytes = new byte [0];
try {
byte [] buffer = new byte[4096];
ByteArrayOutputStream outs = new ByteArrayOutputStream();
int read = 0;
while ((read = ins.read(buffer)) != -1 ) {
outs.write(buffer, 0, read);
}
ins.close();
outs.close();
availableBytes = outs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return availableBytes;
}
}
|
| |
It gives the following output,
[65, 66, 67, 32, 65, 66, 67, 32, 65, 66, 67, 13, 10, 65, 66, 67, 32, 65,
66, 67, 32, 65, 66, 67, 13, 10, 65, 66, 67, 32, 65, 66, 67, 32, 65, 66, 67]
ABC ABC ABC
ABC ABC ABC
ABC ABC ABC
|
|