Filter Streams   «Prev 

ByteArrayInputStream Constructors

public ByteArrayInputStream(byte buffer[])
public ByteArrayInputStream(byte buffer[], int offset, int length)

The first constructor uses the entire buffer array as an input stream.
The second constructor only uses the number of bytes specified in the length argument, starting with the byte at offset.

ByteArrayInputStream

ByteArrayInputStream is 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(byte array [ ])
ByteArrayInputStream(byte array [ ], int start, int numBytes)

Modern Java
Here, array is the input source. The second constructor creates an InputStream from a subset of the byte array that begins with the character at the index specified by start and is numBytes long.
The close( ) method has no effect on a ByteArrayInputStream. Therefore, it is not necessary to call close( ) on a ByteArrayInputStream, but doing so is not an error. The following example creates a pair of ByteArrayInputStreams, initializing them with the byte representation of the alphabet:
// Demonstrate ByteArrayInputStream.
import java.io.*;
class ByteArrayInputStreamDemo {
 public static void main(String args[]) {
  String tmp = "abcdefghijklmnopqrstuvwxyz";
  byte b[] = tmp.getBytes();
  ByteArrayInputStream input1 = new ByteArrayInputStream(b);
  ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
 }
}

The input1 object contains the entire lowercase alphabet, whereas input2 contains only the first three letters.A ByteArrayInputStream implements both mark( ) and reset( ). However, if mark() has not been called, then reset( ) 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 the reset( ) method to read the same input twice. In this case, the program reads and prints the letters 'abc' once in lowercase and then again in uppercase.
import java.io.*;
class ByteArrayInputStreamReset {
 public static void main(String args[]) {
  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();
}

This example first reads each character from the stream and prints it as-is in lowercase. It then resets the stream and begins reading again, this time converting each character to uppercase before printing. Here is the output:
abc
ABC