Java-FileWriter

FileWriter

FileWriter class provides the functionality of writing character into a file. In the following program, an object is created for FileWriter class by passing the data file name output.txt as the argument for its constructor. Then the alphabets are written in this data file, by invoking the write( ) method of FileWriter class. Finally, the file output.txt is closed.

Input / Output Exceptions

When creating files and performing input/output operations on them, the system may generate input/output related exceptions. Each input/output statement or group of input/output statements must have an exception handler around it or the method must declare that it throws an IOException. Proper use of exception handlers would help us identify and locate input/output errors more effectively.

Program

Program Source

import java.io.FileWriter;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args)  {
        
        FileWriter fw = null;
        char data[] = {'A','1','B','2','C','3','D','4','E','5'};
        
        try{
            fw = new FileWriter("output.txt");
            fw.write(data);
            
        }catch(IOException io)
        {
            System.out.println("Exception : "+io);
            
        }finally{
            
            try{
                fw.close();
                
            }catch(IOException io)
            {
                System.out.println("Exception : "+io);
            }
        }
    }
}

Leave a Comment