Tuesday, October 16, 2012

Java Reader example

Java Reader

Java Reader is an abstract class to read character based data streams. It is the base class of various reader classes. Some of the classes are as follows,
  1. Java BufferedReader
  2. Java FileReader
  3. Java StringReader
  4. Java InputStreamReader
This class provides two constructors. Both the constructors have java protected access modifier.
  1. reader()
  2. reader(Object lock)
The first constructor do not accepts any parameter and critical sections are synchronized by the reader itself. The second constructor accepts single parameter as an object to synchronize the critical sections.
This class provides some useful and basic methods as follows,
  1. read() : It is used to read a single character.
  2. read(char[] charbuf) : It is used to read an array of characters.
  3. read(char[] charbuf, int off, int len) : It is used to read a character array from the given offset till len number of characters.
  4. ready() : It is used to tell whether stream is ready to read.
  5. reset() : It is used to reset the stream.
  6. mark(int markposition) : It is used to mark at the given position in the stream.
  7. markSupported() : It is used to retrieve whether the stream supports the mark function.
  8. skip(long n) : It is used to skip n characters.
  9. close() : It is used to close the stream.
All the above functions throws java IOException.


Example:

package com.javaeschool.javaexamples.io;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/** * * @author Murali
*/
public class JavaReaderExample
{
public static void main(String args[])
{
Reader readerObj = null;
File readerFile = null;
int s;
char ch;
boolean ready;
try{
readerFile = new File("D:\\wFile.txt");
readerObj = new FileReader(readerFile);
ready = readerObj.ready();
System.out.println("Is stream ready to read? : " + ready);
System.out.println("Reading data from file..!!");
s = readerObj.read();
ch = (char)s;
while(s != -1)
{
System.out.print(ch);
s = readerObj.read();
ch = (char)s;
}
System.out.println();
}
catch(IOException e)
{
System.out.println("Exception caught..!!");
e.printStackTrace();
}
finally
{
try
{//closing objects
System.out.println("Closing object..!!");
readerObj.close();
}
catch(IOException ioe)
{
System.out.println("IOException caught..!!");
ioe.printStackTrace();
}
}
}
}



Output

Is stream ready to read? : true
Reading data from file..!!This is first string.This string will append to first string.
Closing object..!!

No comments:

Post a Comment