The Wayback Machine - https://web.archive.org/web/20240905185636/https://www.geeksforgeeks.org/java-io-reader-class-java/
Open In App

Java.io.Reader class in Java

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java Reader class is an abstract class for reading character streams. The only methods that a subclass must implement are read(char[], int, int), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both. 

Constructors in Java Reader Class

There are two constructors used with Java Reader Class as mentioned below:

  • protected Reader(): Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
  • protected Reader(Object lock): Creates a new character-stream reader whose critical sections will synchronize on the given object.

Methods in 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

Parameters:
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()

Returns:
true if and only if this stream supports the mark operation.

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

Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), 
or -1 if the end of the stream has been 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

Parameters:
cbuf - Destination buffer

Returns:
The number of characters read, or -1 if the end of the stream has been 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

Parameters:
cbuf - Destination buffer
off - Offset at which to start storing characters
len - Maximum number of characters to read

Returns:
The number of characters read, or -1 if the end of the stream has been 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.

Syntax :public int read(CharBuffer target) throws IOException

Parameters:
target - the buffer to read characters into

Returns:
The number of characters added to the buffer, 
or -1 if this source of characters is at its end

Throws:
IOException 
NullPointerException
ReadOnlyBufferException

8. boolean ready()

Tells whether this stream is ready to be read.

Syntax :public boolean ready() throws IOException

Returns:
True if the next read() is guaranteed not to block for input, false otherwise. 
Note that returning false does not guarantee that the next read will block.

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().

Syntax :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
          
Parameters:
n - The number of characters to skip

Returns:
The number of characters actually skipped

Throws:
IllegalArgumentException - If n is negative.
IOException

Example

Java




// Java program demonstrating Reader methods
import java.io.*;
import java.nio.CharBuffer;
import java.util.Arrays;
  
// Driver Class
class ReaderDemo {
    // Main function
    public static void main(String[] args)
        throws IOException
    {
        Reader r = new FileReader(" file.txt & quot;);
        PrintStream out = System.out;
        char c[] = new char[10];
        CharBuffer cf = CharBuffer.wrap(c);
  
        // illustrating markSupported()
        if (r.markSupported()) {
            // illustrating mark()
            r.mark(100);
            out.println("
                        mark method is supported & quot;);
        }
        // skipping 5 characters
        r.skip(5);
  
        // checking whether this stream is ready to be read.
        if (r.ready()) {
            // illustrating read(char[] cbuf,int off,int
            // len)
            r.read(c, 0, 10);
            out.println(Arrays.toString(c));
  
            // illustrating read(CharBuffer target )
            r.read(cf);
            out.println(Arrays.toString(cf.array()));
  
            // illustrating read()
            out.println((char)r.read());
        }
        // closing the stream
        r.close();
    }
}


Output

[f, g, h, i, g, k, l, m, n, o]
[p, q, r, s, t, u, v, w, x, y]
z

Implementation of Reader Classes

Some of the implementations of Reader classes in Java are mentioned below:



Previous Article
Next Article

Similar Reads

Reader ready() method in Java with Examples
The ready() method of Reader Class in Java is used to check whether this Reader is ready to be read or not. It returns a boolean which states if the reader is ready. Syntax: public void ready() Parameters: This method does not accepts any parameters Return Value: This method returns a boolean value which tells if this Reader is ready to be read or
3 min read
Reader read(char[]) method in Java with Examples
The read(char[]) method of Reader Class in Java is used to read the specified characters into an array. This method blocks the stream till: It has taken some input from the stream.Some IOException has occurredIt has reached the end of the stream while reading. Syntax: public int read(char[] charArray) Parameters: This method accepts a mandatory par
3 min read
Reader read(char[], int, int) method in Java with Examples
The read(char[], int, int) method of Reader Class in Java is used to read the specified length characters into an array at a specified offset. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public int read(char[] charArray, int of
3 min read
Reader read(CharBuffer) method in Java with Examples
The read(CharBuffer) method of Reader Class in Java is used to read the specified characters into a CharBuffer instance. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public int read(CharBuffer charBuffer) Parameters: This method
2 min read
Reader read() method in Java with Examples
The read() method of Reader Class in Java is used to read a single character from the stream. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. This method is declared as abstract method. It means that the subclasses of Reader abstract class
3 min read
Reader close() method in Java with Examples
The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources If the stream is already closed, it will have no effect. If any read or other similar operation is performed on
2 min read
Reader mark(int) method in Java with Examples
The mark() method of Reader Class in Java is used to mark the stream as the checkpoint from where the stream read will start, once reset() is called. This method is not supported by all subclasses of Reader class. Syntax: public void mark(int readAheadLimit) Parameters: This method accepts a mandatory parameter readAheadLimit which is the limit on
3 min read
Reader reset() method in Java with Examples
The reset() method of Reader Class in Java is used to reset the stream. After reset, if the stream has been marked, then this method attempts to reposition it at the mark, else it will try to position it to the starting. Syntax: public void reset() Parameters: This method do not accepts any parameter. Return Value: This method do not returns any va
3 min read
Reader skip(long) method in Java with Examples
The skip(long) method of Reader Class in Java is used to skip the specified number of characters on the stream. This number of characters is specified as the parameter. If it reaches the end of the stream by skipping, it will block the stream till it gets some characters, or throw IOException. Syntax: public long skip(long numberOfChar) Parameters:
3 min read
Reader markSupported() method in Java with Examples
The markSupported() method of Reader Class in Java is used to check whether this Reader is supports mark() operation or not. It returns a boolean which states if the reader is mark supported. Syntax: public boolean markSupported() Parameters: This method does not accepts any parameters Return Value: This method returns a boolean value which tells i
2 min read
Console reader() method in Java with Examples
The reader() method of Console class in Java is used to retrieve the unique Reader object which is associated with the console. This reader() method is generally used by sophisticated applications. Simple applications that require only line oriented reading, normally use readLine() method instead of reader() method. Syntax: public Reader reader() P
2 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), "GeeksforGeeks"); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet<String, String, String, String> quartet = new Quartet<String, String, String, String>( "Quartet", "Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet<String, String, String> triplet = new Triplet<String, String, String>( "Triplet 1", "1", "GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println("Hello"); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Article Tags :
Practice Tags :