BufferedWriter Class in Java

In this guide, we'll understand how to use BufferedWriter class in Java with an example.

1. Introduction 

The BufferedWriter class, found within the java.io package, is designed to write text to a character-output stream, buffering characters to provide efficient writing of single characters, arrays, and strings. It’s especially beneficial when making frequent writes. 

2. Benefits of Using BufferedWriter 

Performance Boost: BufferedWriter reduces the I/O operations by writing chunks of characters instead of one at a time. This translates into a noticeable performance enhancement. 

Flexibility: From files to console outputs, it can wrap around various writers. 

3. Constructing a BufferedWriter 

A common practice is to pair BufferedWriter with FileWriter:

FileWriter writer = new FileWriter("output.txt");
BufferedWriter buffered = new BufferedWriter(writer);

4. Key Methods 

Some essential functions of BufferedWriter include: 

  • write(int c): Writes a single character. 
  • write(char[] cbuf, int off, int len): Writes a portion of an array of characters. 
  • write(String s, int off, int len): Writes a portion of a string. 
  • newLine(): Writes a line separator. The line separator string is defined by the system property line.separator
  • flush(): Flushes the buffer to the underlying stream. 
  • close(): Closes the writer. 

5. A Simple Example 

To solidify understanding, let's illustrate the use of BufferedWriter:

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

public class BufferedWriterExample {

    public static void main(String[] args) {
        String filename = "outputFile.txt";

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
            
            bw.write("Hello, BufferedWriter!");
            bw.newLine();
            bw.write("Java I/O is interesting.");

            System.out.println("Text successfully written to " + filename);

        } catch (IOException e) {
            System.out.println("Oops! An error occurred: " + e.getMessage());
        }
    }
}

// Expected Output:
// Text successfully written to outputFile.txt

6. Things to Remember 

Flushing/Closing: Always ensure you flush or close the BufferedWriter after using it. Using try-with-resources (as shown in the example) is a good practice. 

Exception Handling: Always handle IOException when working with I/O classes, including BufferedWriter.

7. When to Use BufferedWriter?

Enhanced Writing Efficiency: Opt for BufferedWriter when writing to text files or streams, especially large ones. Its internal buffer minimizes the actual I/O operations by accumulating chunks of characters and writing them in fewer calls, thereby boosting performance. 

Structured Text Writing: BufferedWriter provides the newLine() method, facilitating platform-independent line breaks. This is advantageous when creating or appending to structured text files where delineation between lines is essential. 

Extension of Other Writers: BufferedWriter can encapsulate other character-based writers like FileWriter or OutputStreamWriter, endowing them with buffered writing functionality. This layered design allows you to combine the source of the data with the efficient writing benefits of buffering.

Related Java I/O Classes

Comments