Chapter 3. Input Streams

java.io.InputStream is the abstract superclass for all input streams. It declares the three basic methods needed to read bytes of data from a stream. It also has methods for closing streams, checking how many bytes of data are available to be read, skipping over input, marking a position in a stream and resetting back to that position, and determining whether marking and resetting are supported.

The read( ) Method

The fundamental method of the InputStream class is read( ). This method reads a single unsigned byte of data and returns the integer value of the unsigned byte. This is a number between 0 and 255:

public abstract int read( ) throws IOException

read( ) is declared abstract; therefore, InputStream is abstract. Hence, you can never instantiate an InputStream directly; you always work with one of its concrete subclasses.

The following code reads 10 bytes from the System.in input stream and stores them in the int array data:

int[] data = new int[10];
for (int i = 0; i < data.length; i++) {
  data[i] = System.in.read( );
}

Notice that although read( ) is reading a byte, it returns an int. If you want to store the raw bytes instead, you can cast the int to a byte. For example:

byte[] b = new byte[10];
for (int i = 0; i < b.length; i++) {
  b[i] = (byte) System.in.read( );
}

Of course, this produces a signed byte instead of the unsigned byte returned by the read( ) method (that is, a byte in the range −128 to 127 instead of 0 to 255). As long as you’re clear in ...

Get Java I/O, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.