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,This class provides two constructors. Both the constructors have java protected access modifier.
- reader()
- reader(Object lock)
This class provides some useful and basic methods as follows,
- read() : It is used to read a single character.
- read(char[] charbuf) : It is used to read an array of characters.
- read(char[] charbuf, int off, int len) : It is used to read a character array from the given offset till len number of characters.
- ready() : It is used to tell whether stream is ready to read.
- reset() : It is used to reset the stream.
- mark(int markposition) : It is used to mark at the given position in the stream.
- markSupported() : It is used to retrieve whether the stream supports the mark function.
- skip(long n) : It is used to skip n characters.
- close() : It is used to close the stream.
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