The java.io.Reader Class

You use a reader almost exactly as you use an input stream. Rather than reading bytes, you read characters. The basic read() method reads a specified number of characters from the underlying input stream into an array starting at a given offset:

public abstract int read(char[] buffer, int offset, int length) 
  throws IOException

This read() method returns the number of characters actually read. As with input streams reading bytes, there may not be as many characters available as you requested. Also like the read() method of an input stream, it returns -1 when it detects the end of the data.

This read() method is abstract. Concrete subclasses that read bytes from some source must override this method. An IOException may be thrown if the underlying stream’s read() method throws an IOException or an encoding error is detected.

You can also fill an array with characters using this method:

public int read(char[] buffer) throws IOException

This is equivalent to invoking read(buffer, 0, buffer.length). Thus, it also returns the number of characters read and throws an IOException when the underlying stream throws an IOException or when an encoding error is detected. The following method reads a single character and returns it:

public int read() throws IOException

Although an int is returned, this int is always between and 65,535 and may be cast to a char without losing information. All three read() methods block until some input is available, an I/O error occurs, or the end ...

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.