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.

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