BufferedWriter is useful in writing the sequence or stream of character to a file. The is fast compared to the FileOutputStream which is writing the stream of bytes. This class directly extends from the Writer class. It has two constructors. This class has the option to set the buffer size which is internally used by the BufferedWriter.
- BufferedWriter(Writer out)- Creates a buffered character-output stream that uses a default-sized output buffer.
- BufferedWriter(Writer out, int sz)- Creates a new buffered character-output stream that uses an output buffer of the given size.
Lets look at the example to understand how to use the BufferedWriter for writing into a file.
BufferedWriterExample.java
package javabeat.net.core; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Java BufferedWriter Example * * @author Krishna * */ public class BufferedWriterExample { /** * @param args */ public static void main(String[] args) throws IOException { //Create file instance File file = new File("NewTextFile.txt"); //Create FileWriter instance FileWriter fileWriter = new FileWriter(file,false); //Create BufferedWriter instance BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); //Write string to a file bufferedWriter.write("This is BufferedWriter Example!!"); //Write newline character bufferedWriter.write("\n"); //Write using Offset and length in the string bufferedWriter.write("Whole Text, Only Part is Written using Offset and Length",5,20); //Close the file writer object bufferedWriter.close(); } }
The new file would have created with the below content if you run the above example program.
NewTextFile.txt
This is BufferedWriter Example!! Text, Only Part is