Java BufferedWriter Example

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.



 * 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

		//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


The new file would have created with the below content if you run the above example program.

This is BufferedWriter Example!!
 Text, Only Part is



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.