How to write to file in Java – BufferedWriter
Published: June 2, 2010 , Updated: August 9, 2011 , Author: mkyong
In Java, BufferedWriter is a character streams class to handle the character data. Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file.
package com.mkyong.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFileExample { public static void main( String[] args ) { try{ String content = "This is the content to write into file"; File file =new File("filename.txt"); //if file doesnt exists, then create it if(!file.exists()){ file.createNewFile(); } FileWriter fw = new FileWriter(file.getName()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Done"); }catch(IOException e){ e.printStackTrace(); } } }






Hi – Thanks for the sample. Would you happen to know if there is any reason to also close the FileWriter?
Also – Shouldn’t we be closing the streams in a finally clause since if an error occurs in the try we would never get to close()…
finally {
if(br != null) br.close();
if(fw != null) fr.close();
}
Thank you…
[...] Write file with BufferedWriter [...]