Java BufferedWriter Methods: A Complete Guide
Working with text files is a common task in Java development—whether you're generating reports, logging program activity, storing configuration details, or exporting data. While Java provides several classes for file I/O, BufferedWriter stands out as one of the most efficient options for writing text to character-based output streams.
BufferedWriter is part of the java.io package. It enhances performance by reducing the number of physical write operations. The class achieves this by storing characters in an internal buffer and writing them to the file in chunks.
In this article, we’ll explore BufferedWriter in depth and examine every important method it offers—complete with explanations, examples, and best use cases.
1. Introduction to BufferedWriter
BufferedWriter is a subclass of Writer, providing a character-oriented approach to writing text. It is typically paired with FileWriter, though it can wrap any Writer instance.
Why Use BufferedWriter?
Without buffering, every write() call results in direct interaction with the file system. This can be slow and inefficient. BufferedWriter solves this problem by:
- Minimizing disk or stream operations
- Improving performance for large text output
- Supporting convenient methods like
newLine()
Basic Syntax
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
You should always close the writer after use or use try-with-resources:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
writer.write("Hello, world!");
}
2. Key BufferedWriter Methods
BufferedWriter provides several methods inherited from Writer and a few of its own. Let’s explore them one by one.
3. write(String str) Method
Description
This method writes a string to the buffer. It does not automatically append a newline character.
Syntax
public void write(String str) throws IOException
Example
writer.write("Java BufferedWriter Tutorial");
writer.write(" - No newline included automatically.");
When to Use
Use this when writing standard text data without needing manual character-level control.
4. write(char[] cbuf) Method
Description
Writes a character array to the buffer. Efficient for scenarios where data is already stored as a char array.
Syntax
public void write(char[] cbuf) throws IOException
Example
char[] data = {'H', 'e', 'l', 'l', 'o'};
writer.write(data);
5. write(char[] cbuf, int off, int len) Method
Description
Writes a portion of a character array. Useful when dealing with large arrays
where only part of them needs writing.
Syntax
public void write(char[] cbuf, int off, int len) throws IOException
Example
char[] letters = {'A','B','C','D','E','F'};
writer.write(letters, 2, 3); // Writes "CDE"
6. write(int c) Method
Description
Writes a single character (represented by an integer). This is rarely used in bulk writing, but helpful for low-level operations.
Syntax
public void write(int c) throws IOException
Example
writer.write('A');
writer.write(65); // Also writes 'A'
7. write(String str, int
off, int len)
Description
Writes a specific portion of a string.
Syntax
public void write(String str, int off, int len) throws IOException
Example
String message = "BufferedWriter Methods in Java";
writer.write(message, 0, 11); // writes "BufferedWri"
Use Case
Great for partial content writing or
when slicing repeated output.
8. newLine() Method
Description
Inserts the system-dependent line separator into the output. This is a major advantage over using "\n" because newLine() adjusts automatically to:
- Windows →
\r\n - macOS/Linux/Unix →
\n
Syntax
public void newLine() throws IOException
Example
writer.write("First Line");
writer.newLine();
writer.write("Second Line");
9. flush() Method
Description
Forces any buffered output to be written immediately. If the buffer isn’t full yet,
data may still be sitting in memory.
Syntax
public void flush() throws IOException
Example
writer.write("Important Data");
writer.flush(); // Ensure it gets written immediately
When to Use
- Before closing the writer
- When writing data that must be saved in real time
- When writing logs that require immediate persistence
10. close() Method
Description
Closes the stream and releases system resources. It also automatically flushes the buffer.
Syntax
public void close() throws IOException
Example
writer.close();
Important Note
Once closed, you cannot reopen or reuse the same BufferedWriter object.
11. Full Example Program Using BufferedWriter Methods
Below is a working example
demonstrating multiple methods together.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
writer.write("Java BufferedWriter Methods");
writer.newLine();
char[] array = {'H','e','l','l','o'};
writer.write(array);
writer.newLine();
writer.write(array, 1, 3); // "ell"
writer.newLine();
writer.write("BufferedWriter Example", 0, 10); // "BufferedWr"
writer.newLine();
writer.write(65); // 'A'
writer.newLine();
writer.flush(); // Ensures all content is written
} catch (IOException e) {
e.printStackTrace();
}
}
}
This generates a file containing multiple types of outputs using different write methods.
12. When Should You Use BufferedWriter?
BufferedWriter is ideal when:
✔ Writing large amounts of text
Its buffering minimizes disk I/O operations.
✔ Writing log files
Frequent log entries benefit from
buffer-based batching.
✔ Handling character-based data
Perfect for text files, configuration
files, or code generation.
✔ Adding system-independent new lines
newLine() ensures portability.
13. Advantages of BufferedWriter
1. Faster Performance
Buffering reduces the number of write operations, significantly improving speed.
2. System-dependent New Line
newLine() saves you from hardcoding line breaks.
3. Flexibility with Writer Objects
Can wrap:
- FileWriter
- OutputStreamWriter
- PrintWriter
4. Easy to Use
Simple API with intuitive methods.
14. Limitations of BufferedWriter
1. Character-only Data
BufferedWriter works with characters—not binary data.
2. Must Be Closed Properly
Failure to close it may cause
data loss due to unflushed buffers.
3. No Built-in Formatting
Unlike PrintWriter, BufferedWriter doesn’t provide formatted output like printf().
15. BufferedWriter vs FileWriter
| Feature | FileWriter | BufferedWriter |
|---|---|---|
| Performance | Slower | Faster due to buffering |
| Buffer | No | Yes |
| Methods | Basic | Includes newLine() |
| Best For | Small writes | Large text writes |
16. Best Practices
✔ Use try-with-resources
Ensures flushing and closing automatically.
✔ Combine with PrintWriter When Needed
If formatting is needed:
PrintWriter p = new PrintWriter(new BufferedWriter(new FileWriter("text.txt")));
✔ Call flush() When Writing Critical Data
✔ Avoid Excessive write() Calls in Loops
Accumulate text when possible.
Conclusion
BufferedWriter is one of the most powerful and efficient tools for writing text files in Java. Its buffering mechanism significantly enhances performance, especially for large-scale output operations. With useful methods like write(), newLine(), flush(), and close(), BufferedWriter provides an easy-to-use yet highly flexible API for developers.
Whether you're creating logs, exporting data, writing reports, or generating text-based files, mastering BufferedWriter methods will greatly improve the quality and performance of your file-handling code.
