Java ByteArrayInputStream Class
A byte array input stream creates a byte array buffer in memory, and the data read from the input stream is saved in this byte array buffer. There are several ways to create a byte array input stream object.
Created by receiving a byte array as a parameter:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another way to create it is to receive a byte array and two integer variables off and len, where off indicates the first byte to read and len indicates the length of bytes to read.
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a,
int off,
int len)
After successfully creating the byte array input stream object, you can refer to the methods in the list below to perform read or other operations on the stream.
| No. | Method Description |
|---|---|
| 1 | **public int read() ** |
| Reads the next data byte from this input stream. | |
| 2 | public int read(byte[] r, int off, int len) |
Reads up to len data bytes from this input stream into the byte array. |
|
| 3 | public int available() |
| Returns the number of bytes that can be read from this input stream without blocking. | |
| 4 | public void mark(int read) |
| Sets the current mark position in the stream. | |
| 5 | public long skip(long n) |
Skips n input bytes from this input stream. |
Example
The example below 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 ) {
// Get user input value
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 compilation and execution results of the above example 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
Java Stream