Java ByteArrayInputStream class
Byte array input stream in memory to create a buffer byte array input stream to read data from an array of bytes stored in the buffer. Create a byte array input stream objects There are several ways.
Receive byte array as a parameter to create:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another way to create is to receive a byte array, and two integer variable off, len, off represents the first byte read, len indicates the length of bytes read.
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len)
After the byte array input stream object is successfully created, you can see the following list of methods, convection read operation or other operations.
No. | Method Description |
---|---|
1 | public int read () This input stream to read the next data byte. |
2 | public int read (byte [] r , int off, int len) The most len bytes of data from this input stream into an array of bytes. |
3 | public int available () Returns may not be blocking this input the number of bytes read from the stream. |
4 | public void mark (int read) Set the stream at the current marker position. |
5 | public long skip (long n) From this input stream to skip n bytes of input. |
Examples
The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream:
import java.io.*; public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // 获取用户输入值 bOutput.write(System.in.read()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x= 0 ; x < b.length; x++) { // 打印字符 System.out.print((char)b[x] + " "); } System.out.println(" "); int c; ByteArrayInputStream bInput = new ByteArrayInputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c= bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } } }
The above examples compiled results are as follows:
asdfghjkly Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y