dsa

Java Reader

In this tutorial, we will learn about the Java Reader, its subclasses, its constructors and its methods with the help of an example.

Reader is an abstract class for reading character streams. Since, it is an abstract class ,so we to use its derived classes or child classesfor creating it's objects.

Child classes of Reader class

Constructors of Reader

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

Methods

MethodsDesciption
protected close()Closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit)Marks the present position in the stream.
boolean markSupported()Tells whether this stream supports the mark() operation.
int read()Reads a single character.
int read(char[] cbuf)Reads characters into an array.
abstract int read(char[] cbuf, int off, int len)Reads characters into a portion of an array.
int read(CharBuffer target)Attempts to read characters into the specified character buffer.
boolean ready()Tells whether this stream is ready to be read.
void reset()Resets the stream.
long skip(long n)Skips characters.

Examples :

Suppose we have a file named input.txt with the following content.


This file consists of one line only.

Now, Lets read this file.


import java.io.Reader;
import java.io.FileReader;

class Codemistic 
{
    	public static void main(String[] args) 
	{

        	// Creates an array of character
        	char[] array = new char[100];

        	try 
		{
            		// Creates a reader using the FileReader
            		Reader line = new FileReader("input.txt");

            		// Checks if reader is ready 
            		System.out.println("Is there any input in the stream?  " + line.ready());

            		// Reads characters
            		line.read(array);
            		System.out.println("Data in the stream:");
            		System.out.println(array);

            		// Closes the reader
            		line.close();
        	}
        	catch(Exception e) 
		{
        	    	e.getStackTrace();
        	}
    	}	
}

Output :

Is there any input in the stream?  true
Data in the stream:
This file consists of one line only.