ByteArrayInputStream - sample program in Java

By: Baski Viewed: 154108 times  Printer Friendly Format    


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)

Here, array is the input source. The second constructor creates an InputStream from a subset of your byte array that begins with the character at the index specified by start and is numBytes long.

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[]) throws IOException {
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, while 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, 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();
}
}
}

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's the output:

abc
ABC

This tutorial is an extract from the "The Complete Reference Part 2 by Herbert Schildt".



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial