Methods of Reader

The Reader class provides different methods that are implemented by its subclasses. Here are some of the commonly used methods:

  1. ready() - checks if the reader is ready to be read.
  2. read(char[] array) - reads the characters from the stream and stores in the specified array.
  3. read(char[] array, int start, int length) - reads the number of characters equal to length from the stream and stores in the specified array starting from the start.
  4. mark() - marks the position in the stream up to which data has been read.
  5. reset() - returns the control to the point in the stream where the mark is set.
  6. skip() - discards the specified number of characters from the stream.

Here is how we can implement Reader using the FileReader class. Suppose we have a file named input.txt with the following content.


\begin{lstlisting}
This is a line of text inside the file.
\end{lstlisting}

Let’s try to read this file using FileReader (a subclass of Reader).


\begin{lstlisting}
import java.io.Reader;
import java.io.FileReader;
\par
class ...
...e();
}
\par
catch( Exception e ) {
e.getStackTrace();
}
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Is there data in the stream ? true
Data in the stream :
This is a line of text inside the file .
\end{lstlisting}

In the above example, we have created a reader using the FileReader class. The reader is linked with the file input.txt.