Tech and Media Labs
This site uses cookies to improve the user experience.

Java IO: BufferedWriter

Jakob Jenkov
Last update: 2015-09-09

The Java BufferedWriter class ( provides buffering to Writer instances. Buffering can speed up IO quite a bit. Rather than write one character at a time to the network or disk, the BufferedWriter writes a larger block at a time. This is typically much faster, especially for disk access and larger data amounts.

BufferedWriter Example

To add buffering to a Writer simply wrap it in a Java BufferedWriter. Here is how that looks:

BufferedWriter bufferedWriter = 
    new BufferedWriter(new FileWriter("c:\\data\\output-file.txt"));

This example creates a BufferedWriter which writes characters to a FileWriter. Simple, isn't it?

BufferedWriter Buffer Size

You can set the buffer size to use internally by the Java BufferedWriter. You provide the size as a constructor parameter, like this:

int bufferSize = 8 * 1024;
BufferedWriter bufferedWriter = 
    new BufferedWriter(
        new FileWriter("c:\\data\\output-file.txt"),

This example sets the internal buffer of the BufferedWriter to 8 KB. It is best to use buffer sizes that are multiples of 1024 bytes. That works best with most built-in buffering in hard disks etc.

Except for adding buffering to your input streams, BufferedWriter behaves pretty much like a Writer. The BufferedWriter adds one extra method though: The newLine() method which can write a new-line character to the underlying Writer. In addition, you may need to call flush() if you need to be absolutely sure that the characters written until now is flushed out of the buffer and onto the network or disk.

Closing a BufferedWriter

When you are finished writing characters to the Java BufferedWriter you should remember to close it. Closing a BufferedWriter will also close the Writer instance to which the BufferedWriter is writing.

Closing a BufferedWriter is done by calling its close() method. Here is how closing a BufferedWriter looks:


You can also use the try-with-resources construct introduced in Java 7. Here is how to use and close a BufferedWriter looks with the try-with-resources construct:

FileWriter output = new FileWriter("data/data.bin");

try(BufferedWriter bufferedWriter =
    new BufferedWriter(output)){

    bufferedWriter.write("Hello World");


Notice how there is no longer any explicit close() method call. The try-with-resources construct takes care of that.

Notice also that the first FileWriter instance is not created inside the try-with-resources block. That means that the try-with-resources block will not automatically close this FileWriter instance. However, when the BufferedWriter is closed it will also close the OutputStream instance it writes to, so the FileWriter instance will get closed when the BufferedWriter is closed.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC