Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must extend it and implement its methods. The read() is the key method for reading characters.
Example: The below Java Program demonstrates how to read a text file character by character using the Reader class.
Java import java.io.*; public class Geeks { public static void main(String[] args) { // Try-catch block for exception handling try { // Create a FileReader object // which is a subclass of Reader Reader r = new FileReader("example1.txt"); // Read one character at a time from the file int data = r.read(); while (data != -1) { // Convert the int to char and print System.out.print((char)data); data = r.read(); } // Close the reader r.close(); } catch (Exception ex) { // Handle any IO exceptions System.out.println("An error occurred: " + ex.getMessage()); } } }
Output :
Note: To ensure the program runs correctly, create a file named example1.txt
in the working directory.
Once the working directory is determined, create the file example1.txt
in that location. Add the following content to the file, or you can add any text.
Hello welcome to Geeks for Geeks
Save the file and run the program. The program will read and display the contents of example1.txt
as output.
Declaration of Reader Class
Declaration of Reader class is given below:
public abstract class Reader implements Readable, Closeable
Key Points
1. abstract class
- The Reader class is an abstract class means it cannot be instantiated directly.
- It is designed to be extended by either classes like FileReader, BufferedReader.
2. Implements Readable
The Reader class implements Readable Interface
int read(CharBuffer cb) throws IOException;
3. Implements Closeable
The Reader class implements Closeable Interface
void close() throws IOException;
Constructors of Reader Class
There are two constructors used with Java Reader Class as mentioned below:
1. protected Reader()
Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
2. protected Reader(Object lock)
- Creates a new character-stream reader whose critical sections will synchronize on the given object.
- Parameter: The object used to synchronize the operations of the Reader.
Methods of Java Reader Class
1. abstract void close()
Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.
Syntax:
public abstract void close() throws IOException
Throws: IOException
2. void mark(int readAheadLimit)
Marks the present position in the stream.Subsequent calls to reset() will attempt to reposition the stream to this point. Not all character-input streams support the mark() operation.
Syntax:
public void mark(int readAheadLimit) throws IOException
- Parameter: readAheadLimit - Limit on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail.
- Throws: IOException
3. boolean markSupported()
Tells whether this stream supports the mark() operation. The default implementation always returns false. Subclasses should override this method.
Syntax:
public boolean markSupported()
Return Type:
- Return True if the input stream supports mark() and reset() methods.
- Return False is the input stream does not support these methods.
4. int read()
Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached. Subclasses that intend to support efficient single-character input should override this method.
Syntax:
public int read() throws IOException
Return Type:
- Return the next byte of data as an integer in the range 0 to 255.
- Return -1 if the end of the stream is reached
Throws: IOException
5. int read(char[] cbuf)
Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Syntax:
public int read(char[] cbuf) throws IOException
Parmeter:
- char[] cbuf: A character array provided by the caller where the characters read from the stream will be stored.
Return Type:
- Return the number of character actually read.
- Return -1 if the end of the stream is reached.
Throws: IOException
6. abstract int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Syntax:
public abstract int read(char[] cbuf,int off,int len) throws IOException
Parameter:
- char[] cbuf: The character array where the characters will be stored.
- int off: The starting index in the array where the first character will be stored.
- int len: Maximum number of characters to read
Return Type:
- Return the number of character actually read and stored in the buffer.
- Return -1 if the end of the stream is reached.
Throws: IOException
7. int read(CharBuffer target)
Attempts to read characters into the specified character buffer. The buffer is used as a repository of characters as-is: the only changes made are the results of a put operation. No flipping or rewinding of the buffer is performed.
Synatx:
public int read(CharBuffer target) throws IOException
Parameter:
- CharBuffer target: A
CharBuffer
into which characters are read.
Return type:
- The number of characters read into the buffer.
- Return -1 if the end of the stream is reached.
Throws:
- IOException
- NullPointerException
- ReadOnlyBufferException
8. boolean ready()
Tells whether this stream is ready to be read.
Synatx:
public boolean ready() throws IOException
Return Type:
- Return True if the stream is ready to read.
- Return False if the stream is not ready.
Throws: IOException
9. void reset()
Resets the stream. If the stream has been marked, then attempt to reposition it at the mark. If the stream has not been marked, then attempt to reset it in some way appropriate to the particular stream, for example by repositioning it to its starting point. Not all character-input streams support the reset() operation, and some support reset() without supporting mark().
Synatx:
public void reset() throws IOException
Throws: IOException
10. long skip(long n)
Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of the stream is reached.
Syntax:
public long skip(long n) throws IOException
Parameter: long n: The number of bytes or characters to skip in the stream. If n
is negative, the method does nothing
Return Type: Return the number of character actually skipped.
Throws:
- IOException
- IllegalArgumentException(if n is negative)
Example: The below program demonstrate the working of various functionalities of the Reader class in Java.
Java import java.io.*; import java.nio.CharBuffer; import java.util.Arrays; public class Geeks { public static void main(String[] args) throws IOException { // Open a file reader Reader r = new FileReader("file.txt"); PrintStream out = System.out; // Create a character array and CharBuffer char[] buffer = new char[10]; CharBuffer charBuffer = CharBuffer.wrap(buffer); // Check if the reader supports marking if (r.markSupported()) { r.mark(100); // Mark the current position out.println("mark method is supported"); } // Skip 5 characters in the stream r.skip(5); // Check if the stream is ready to read if (r.ready()) { // Read 10 characters into the buffer r.read(buffer, 0, 10); out.println("Buffer after reading 10 chars: " + Arrays.toString(buffer)); // Read characters into the CharBuffer r.read(charBuffer); out.println( "CharBuffer contents: " + Arrays.toString(charBuffer.array())); // Read a single character out.println("Next character: " + (char)r.read()); } // Close the reader r.close(); } }
Output:
Implementation of Reader Classes
Some of the implementations of Reader classes in Java are mentioned below:
Key Features of Reader Class
- Character-Based Reading: Reader class is used for reading rexr which handles binary data
- Abstract class: we can not create a Readeer object directly, we need to use subclasses like BufferedReader or FileReader.
- Unicode Support: It can read and process Unicode.
Similar Reads
Java Writer Class Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will u
5 min read
Wrapper Classes in Java A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
6 min read
Nested Classes in Java In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
5 min read
Object Class in Java Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
7 min read
Static class in Java Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
3 min read