Skip to Main Content
Java I/O, 2nd Edition
book

Java I/O, 2nd Edition

by Elliotte Rusty Harold
May 2006
Beginner to intermediate content levelBeginner to intermediate
726 pages
19h 57m
English
O'Reilly Media, Inc.
Content preview from Java I/O, 2nd Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java I/O

Java I/O

Elliotte Rusty Harold
Java NIO

Java NIO

Ron Hitchens

Publisher Resources

ISBN: 0596527500Errata PageSupplemental Content