Java-FileReader

FileReader

FileReader class provides the functionality of reading character from a file. In the following program, an object is created for the FileReader class by passing the data file output.txt as the argument for its constructor. Since the alphabets have been written into this data file in the previous program, they are retrieved, one by one, and then displayed on the screen. The read( ) method in the FileReader class reads a single character at a time. This character is stored as the value of the integer type variable getc. If the value of the variable getc is not equal to -1, we cast it to a character and then display it. The -1 indicates the end of the file. If the value of the variable getc is equal to -1, we terminate the loop.

FileReader Constructors

Constructors Description
FileReader(File file) Creates a new FileReader, given the File to read from.
FileReader(String fileName) Creates a new FileReader, given the name of the file to read from.

FileReader Methods

Method Description
int read() Reads a single character.
int read(char[] buf) Reads characters into an array.
int read(char[] buf, int off, int len) Reads characters into a portion of an array.
boolean ready() Tells whether this stream is ready to be read.
long skip(long n) Skips characters.
void close() Closes the stream and releases any system resources associated with it.

Program

Program Source

import java.io.FileReader;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args)  {
        
        FileReader fr = null;
        
        try{
            fr = new FileReader("output.txt");
            int getc;
            while((getc=fr.read())!=-1)
            {
                System.out.print((char)getc+", ");
            }
        }catch(IOException io)
        {
            System.out.println("Exception : "+io);
            
        }finally{
            
            try{
                fr.close();
                
            }catch(IOException io)
            {
                System.out.println("Exception : "+io);
            }
        }
    }
}

Leave a Comment