Reading Writing Text  «Prev  Next»


Lesson 5The ready() and read() methods of the Reader class
ObjectiveExamine the methods of the Reader class used for reading characters.

Java ready() and read() Methods

The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read() and write( ), which read and write characters of data, respectively. Each has a form that is abstract and must be overridden by derived stream classes.

The read( ) methods

The basic read() method reads a single character (which may take between one and four bytes, depending on the character set) and returns the character as an int between 0 and 65,535. It returns -1 if the end-of-stream is seen.

public int read() throws IOException
You can also read many characters into an array of chars. These methods return the number of bytes successfully read or -1 if the end-of-stream occurs.

public int read(char[] cbuf) throws IOException

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

All the read() methods block until some input is available, an I/O error occurs, or the end-of-stream is reached.

ready( ) method

The ready() method returns true if the Reader is ready to be read from, false if it is not. Generally true means the underlying stream has available data.

public boolean ready() throws IOException