Reading Writing Text  «Prev  Next»


Lesson 4Java Reader class
Objective Investigate the fundamental methods of the Reader class.

Java Reader Class

The java.io.Reader class provides text-based input to Java programs. A stream is the source of the bytes containing the text. However, as the bytes are read they are converted into Java chars before being passed on to the other parts of the program. One or more bytes may be read for each character produced.
The methods of the java.io.Reader class are deliberately similar to the methods of the java.io.InputStream class. However, rather than working with bytes, they work with chars.
The main methods of the Reader class are:
  1. ready() and read()
  2. skip() and close()
  3. mark() and reset()

We will be examining each of these methods in the next several lessons.
All of these methods are present in the various subclasses of java.io.Reader.

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 of the stream is reached. You can skip a certain number of characters. This method also blocks until some characters are available. It returns the number of characters skipped or -1 if the end of stream is reached.