Java-BufferedWriter

BufferedWriter

The BufferedWriter class possesses the functionality of writing buffers of characters into a file. In the following program, an object of FileWriter class is first created and associated with the data file output.txt. Then, an object of BufferedWriter class is created. Subsequently, the names of five national parks are stored in the data file output.txt, one at a time, by invoking the write( ) method of the BufferedWriter class. Finally, both the filestream objects are closed.

Program

hh

Program Source

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

class Javaapp {
    
    public static void main(String[] args) {
        
        FileWriter fw = null;
        BufferedWriter bw = null;
        String nationalParks[] = {"1) Kruger National Park",
                                  "2) Royal Natal National Park",
                                  "3) Golden Gate Highlands National Park",
                                  "4) Table Mountain National Park",
                                  "5) Kgalagadi Transfrontier Park"};
        try{
            fw = new FileWriter("output.txt");
            bw = new BufferedWriter(fw);
            int i = 0;
            
            while(i<nationalParks.length)
            {
                bw.write(nationalParks[i]);
                bw.newLine();
                i++;
            }
        }catch(IOException io)
        {
            System.out.println("Exception : "+io);
            
        }finally{
            
            try{
                bw.close();
                fw.close();
            }catch(IOException io)
            {
                System.out.println("Exception : "+io);
            }
        }
    }
}

Leave a Comment