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 is given below:
Key Pointspublic abstract class Reader implements Readable, Closeable
1. abstract class
2. Implements Readable
The Reader class implements Readable Interface
int read(CharBuffer cb) throws IOException;
3. Implements Closeable
The Reader class implements Closeable Interface
Constructors of Reader Classvoid close() throws IOException;
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)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
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:
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:
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:
Return Type:
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:
Return Type:
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
into which characters are read.Return type:
Throws:
Tells whether this stream is ready to be read.
Synatx:
public boolean ready() throws IOException
Return Type:
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:
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:
Some of the implementations of Reader classes in Java are mentioned below:
Key Features of Reader ClassRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4