ByteArrayInputStream
ByteArrayInputStreamis an implementation of an input stream that uses a byte array as
the source. This class has two constructors, each of which requires a byte array to provide the
data source:
ByteArrayInputStream(bytearray[ ])
ByteArrayInputStream(bytearray[ ], intstart, intnumBytes)
Here,arrayis the input source. The second constructor creates anInputStreamfrom a
subset of your byte array that begins with the character at the index specified bystartand
isnumByteslong.
The following example creates a pair ofByteArrayInputStreams, initializing them with
the byte representation of the alphabet:
// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b,0,3);
}
}
Theinput1object contains the entire lowercase alphabet, whileinput2contains only the
first three letters.
AByteArrayInputStreamimplements bothmark( )andreset( ). However, ifmark( )has
not been called, thenreset( )sets the stream pointer to the start of the stream—which in this
case is the start of the byte array passed to the constructor. The next example shows how to
use thereset( )method to read the same input twice. In this case, we read and print the letters
“abc” once in lowercase and then again in uppercase.
import java.io.*;
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
Chapter 19: Input/Output: Exploring java.io 567