In this tutorial you will learn how to write to file using BufferedWriter
Java Write To File BufferedWriter
In this tutorial you will learn how to write to file using BufferedWriter
BufferedWriter is a class of java.io package. This class is used to write texts to a character-output stream. This class stores the characters in a buffer to write into a character-output stream and this feature of makes it efficient for writing of single characters, arrays and strings. For the convenience generally this class should be wrapped around any Writer because, some Writer's write() method's operations may take more time to write. These Writer can be FileWriter, OutputStreamWriter etc. In the example given below I wrapped the FileWriter object in it.
In the example given below at first I have created a File object and wrapped it into the FileWriter object to write the character-output stream. And to write efficiently I have wrapped the FileWriter object in the BufferedWriter. write() method of this class writes the characters, strings, or etc from buffer where this class buffering characters.
Example :
WriteToFileBufferedWriter.java
import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; class WriteToFileBufferedWriter { public static void main(String args[]) throws IOException { WriteToFileBufferedWriter wtfbw = new WriteToFileBufferedWriter(); wtfbw.bufferedWriterExample(); } public void bufferedWriterExample() { BufferedWriter bw = null; try { File file = new File("bufferedWriter.txt"); FileWriter fw = new FileWriter(file); bw = new BufferedWriter(fw); bw.write("This example demonstrates you how to write in a file using BufferedWriter."); } catch (Exception e) { System.out.println(e); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (IOException ex) { ex.printStackTrace(); } } System.out.println("\n ----------**-----Text is written into file successfully-----**------------"); } }
How to Execute this example :
After doing the basic process to execute a java program write simply on command prompt as :
javac WriteToFileBufferedWriter.java to compile the program
And after successfully compilation to run simply type as :
java WriteToFileBufferedWriter
Output :
When you will execute this example a new file will be created at the specified place given by you with containing the text that you are trying to write into the file by java program.