Tuesday, October 28, 2014

Use BufferedWriter write to a file


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

public class BufferedWriterTest {
   
    public static void main(String[] args) throws IOException{
        String fileName = "C:\\tmp\\test.txt";
        File file = new File(fileName);    // File needs fileName
        FileWriter fw =  new FileWriter(file);    // so here use Writer implementing class - FileWriter
        BufferedWriter bw = new BufferedWriter(fw); //Writer can not be initialized b/c it's abstract class
        try {
            bw.write("this is my test file");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            bw.close();    // when close, the content can be written to the file
            fw.close();
        }

       
    }

}

No comments:

Post a Comment