The Reader class in Java is an abstract class used for reading character streams.
In this chapter, we will learn what the Reader class is, why it is used, its declaration, constructors, important methods, and how to read character data using examples.
The Reader class is an abstract class for reading data in the form of characters, and it is used as the base class for all character input stream classes.
It provides common methods to read characters, character arrays, and strings. Classes such as BufferedReader, FileReader, InputStreamReader, and StringReader extend the Reader class to provide concrete implementations.
The following declaration shows how the Reader class is defined in Java.
The Reader class contains a field used for synchronization.
| Modifier and Type | Field | Description |
|---|---|---|
| protected Object | lock | The object used to synchronize operations on this stream. |
The Reader class provides protected constructors that are used by its subclasses.
This constructor creates a new character stream reader whose critical sections synchronize on the reader itself.
Syntax:
Here is the syntax of this constructor:
This constructor creates a new character stream reader whose critical sections synchronize on the specified lock object.
Syntax:
Here is the syntax of this constructor:
The following example shows how the constructors of the Reader class are used indirectly through its subclasses.
The Reader class provides methods to read character data from input streams.
| Modifier and Type | Method | Description |
|---|---|---|
| abstract void | close() | It closes the stream and releases any system resources associated with it. |
| void | mark(int readAheadLimit) | It marks the present position in the stream. |
| boolean | markSupported() | It tells whether this stream supports the mark() operation. |
| int | read() | It reads a single character. |
| int | read(char[] cbuf) | It reads characters into an array. |
| abstract int | read(char[] cbuf, int off, int len) | It reads characters into a portion of an array. |
| int | read(CharBuffer target) | It attempts to read characters into the specified character buffer. |
| boolean | ready() | It tells whether this stream is ready to be read. |
| void | reset() | It resets the stream. |
| long | skip(long n) | It skips characters. |
The following examples demonstrate how the Reader class is used through its subclasses.
This example demonstrates how to read characters from a file using the FileReader class.
file.txt:
I love my country
Output:
I love my country
This example demonstrates how to read text efficiently using the BufferedReader class.
Output:
I love my country
We request you to subscribe our newsletter for upcoming updates.