The read( ) Method

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

public abstract int read() throws IOException

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 to 255). As long as you’re clear in your mind and your code about whether you’re working with signed or unsigned data, you won’t have any trouble. Signed bytes can be converted back to ints in the range to 255 like this:

int i = (b >= 0) ? b : 256 + b;

When you call read(), you also have to catch the IOException that it might throw. As I’ve observed, input and output are often subject to problems outside of your control: disks fail, network cables break, and so on. Therefore, virtually any I/O method can throw an IOException, and read() is no exception. You don’t get an IOException if read() encounters the end of the input stream; in this case, ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.