Java BufferedWriter Class


In Java, writing to files efficiently is an essential task in many applications. The BufferedWriter class, part of the java.io package, is specifically designed to provide efficient writing of text data. By buffering the output, it reduces the number of write operations, improving performance when writing large amounts of text data. In this blog post, we’ll take a deep dive into the BufferedWriter class, explore its functionality, and walk you through examples of its usage.


What is Java BufferedWriter Class?

The BufferedWriter class in Java is a character-based output stream that is used to write text data to a file or another output stream. It is a wrapper around a Writer class (like FileWriter) and provides a buffer to make writing more efficient by minimizing the number of write operations.

Key Features of BufferedWriter:

  • Efficient Writing: It uses an internal buffer to write data in larger chunks, which improves performance when dealing with larger files.
  • Line-based Writing: The newLine() method allows you to add platform-specific newlines to separate lines of text.
  • Works with Character Streams: It is designed to work with character streams and is ideal for writing text files like .txt, .csv, .json, and .xml.
  • Buffered Output: Reduces the number of I/O operations by writing data in larger blocks.

Syntax of BufferedWriter Class

To use BufferedWriter, you need to create an object of BufferedWriter and pass a Writer object (like FileWriter) as a parameter.

BufferedWriter(Writer out)

For example, to write to a file using BufferedWriter, you would pass a FileWriter object to it:

BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));

You can also specify if you want to append to an existing file:

BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true));

How to Use the BufferedWriter Class

The primary method for writing data using BufferedWriter is write(). Additionally, the newLine() method is used to insert new lines. Let's go through some practical examples to better understand how to use this class.

Example 1: Writing Text to a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterExample {
    public static void main(String[] args) {
        BufferedWriter writer = null;

        try {
            // Create a BufferedWriter to write to the file
            writer = new BufferedWriter(new FileWriter("example.txt"));

            // Write data to the file
            writer.write("Hello, World!");
            writer.newLine(); // Insert a new line
            writer.write("Welcome to the BufferedWriter class example.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the BufferedWriter
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • The BufferedWriter is created with a FileWriter to write to the example.txt file.
  • The write() method is used to write the text to the file.
  • The newLine() method is called to insert a platform-specific newline character (it could be \n on Unix-based systems or \r\n on Windows).
  • The finally block ensures that the BufferedWriter is properly closed after writing.

BufferedWriter with Append Mode

If you want to append data to an existing file, you can use the second constructor of FileWriter, which accepts a boolean parameter append. When set to true, the BufferedWriter will append new data instead of overwriting the existing file content.

Example 2: Appending Data to a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterAppendExample {
    public static void main(String[] args) {
        BufferedWriter writer = null;

        try {
            // Create a BufferedWriter in append mode
            writer = new BufferedWriter(new FileWriter("example.txt", true));

            // Append new data to the file
            writer.newLine(); // Insert a new line
            writer.write("This content is being appended to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the BufferedWriter
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • In this example, we pass true as the second parameter to FileWriter, which tells the BufferedWriter to append data instead of overwriting the file.
  • The new text is added at the end of the file after a newline.

BufferedWriter with Multiple Lines of Text

To write multiple lines of text to a file, you can use the write() method multiple times and call newLine() in between to separate each line.

Example 3: Writing Multiple Lines to a File

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterMultipleLines {
    public static void main(String[] args) {
        BufferedWriter writer = null;

        try {
            // Create a BufferedWriter to write to the file
            writer = new BufferedWriter(new FileWriter("multipleLines.txt"));

            // Write multiple lines to the file
            writer.write("This is the first line.");
            writer.newLine();
            writer.write("This is the second line.");
            writer.newLine();
            writer.write("This is the third line.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the BufferedWriter
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  • We use write() to write each line and newLine() to add a newline between them.
  • This is useful when you need to write structured data, like CSV or plain text, with each record on a new line.

BufferedWriter and Performance

The BufferedWriter class is specifically designed to enhance performance. By buffering the output and writing data in larger chunks, it minimizes the number of I/O operations required, making it more efficient than writing one character at a time with FileWriter or PrintWriter.

Example 4: Performance Comparison between FileWriter and BufferedWriter

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class PerformanceComparison {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        // Using FileWriter
        try (FileWriter writer = new FileWriter("largefile.txt")) {
            for (int i = 0; i < 1000000; i++) {
                writer.write("This is a test line.\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("FileWriter time: " + (endTime - startTime) + " milliseconds");

        startTime = System.currentTimeMillis();

        // Using BufferedWriter
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("largefile.txt"))) {
            for (int i = 0; i < 1000000; i++) {
                writer.write("This is a test line.\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        endTime = System.currentTimeMillis();
        System.out.println("BufferedWriter time: " + (endTime - startTime) + " milliseconds");
    }
}

Explanation:

  • This comparison shows how much faster BufferedWriter can write large amounts of data compared to FileWriter.
  • As expected, the buffered writer will be much faster because it reduces the number of write operations.

Best Practices When Using BufferedWriter

  1. Always Close the BufferedWriter: Always close the BufferedWriter in a finally block or use the try-with-resources statement to avoid resource leaks.
  2. Use New Line Properly: Use the newLine() method to add new lines to your file to ensure platform-specific line breaks.
  3. Write in Larger Chunks: Avoid writing characters one by one. Instead, write larger chunks of data (like entire lines or blocks) for better performance.
  4. Handle Exceptions: Always handle IOException when writing to a file to deal with any potential issues like file permissions or disk space.