In this section we will discuss about the Reader class in Java.
Reader class is an abstract class in java.io package provided for reading the character streams. This class is a super class of all the classes which are involved in or to facilitate to read (input) the character streams. Classes descended from this class may overrides the methods of this class but the method read(char[], int, int) and close() must be implemented by the subclasses. This class can not be instantiated directly.
Constructor of Reader
| Reader() | This is a default constructor which creates a reader for reading character
streams.
In such type of character streams reader synchronization of critical sections is
depend on the reader itself. Syntax : protected Reader() |
| Reader(Object lock) | A parameterized constructor which creates a reader for reading character
streams. In such type of character streams reader synchronization of critical
sections is depend on the given object. Syntax : protected Reader(Object lock) |
Methods of Reader class
Methods that must be implemented by its subclasses are as follows :
Commonly used methods of this class are as follows :
Example :
An example of Reader class is given here which demonstrate that how character streams reader can be created and how the characters can be read from the stream. In this example I have created a Java class named JavaReaderExample.java into which created an input stream using Reader and FileReader. To read the contents of file used the read() method of Reader class.
Source Code
JavaReaderExample.java
import java.io.Reader;
import java.io.FileReader;
import java.io.IOException;
public class JavaReaderExample
{
public static void main(String args[])
{
Reader rdr = null;
try
{
rdr = new FileReader("file.txt");
int c ;
System.out.println();
System.out.println("***** OUTPUT *****");
System.out.println();
while((c= rdr.read()) != -1)
{
System.out.print((char) c);
}
System.out.println();
}
catch(Exception ex)
{
System.out.println(ex);
}
finally
{
if(rdr != null)
{
try
{
rdr.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}// end finally
}// end main
}// end class
Output
When you will execute the above code you will get the output as follows :

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Java IO Reader
Post your Comment