BufferedWriter Class in Java: Fast Text Writing
Writing thousands of short lines directly to a file makes the program talk to the operating system thousands of times. BufferedWriter collects text in memory and writes it in large blocks, and its newLine() method writes the correct line separator for the platform.
This tutorial covers its constructors and methods, and two examples.
1. What Is BufferedWriter in Java?
BufferedWriter extends Writer and wraps another writer, such as a FileWriter or OutputStreamWriter. Text is kept in an internal buffer until the buffer is full, flush() is called or the writer is closed. It was added in Java 1.1.
2. BufferedWriter Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of BufferedWriter
| Constructor | Description |
|---|---|
BufferedWriter(Writer out) | Wraps out with a buffer of the default size. |
BufferedWriter(Writer out, int sz) | Wraps out with a buffer of sz characters. |
For files, Files.newBufferedWriter(path) creates one with UTF-8 encoding in a single call.
4. Commonly Used Methods
| Method | Description |
|---|---|
void write(String s) | Adds text to the buffer. |
void newLine() | Writes the line separator from the line.separator system property. |
void flush() | Writes the buffered text to the wrapped writer. |
void close() | Flushes, then closes the wrapped writer. |
5. Example: Exporting 500 Orders to CSV
A shop exports 500 orders to a CSV file with a header line.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class SalesExport {
public static void main(String[] args) throws IOException {
Path csv = Files.createTempFile("sales", ".csv");
try (BufferedWriter out = Files.newBufferedWriter(csv, StandardCharsets.UTF_8)) {
out.write("order_id,amount");
out.newLine(); // platform line separator
for (int id = 1001; id <= 1500; id++) {
out.write(id + "," + (id % 7) * 100);
out.newLine();
}
} // close() flushes the last block
System.out.println("Lines written: " + Files.readAllLines(csv).size());
System.out.println("Last line: " + Files.readAllLines(csv).getLast()); // getLast(): Java 21
Files.delete(csv);
}
}
Lines written: 501 Last line: 1500,200
How the code works
Files.newBufferedWriter()returns aBufferedWriterthat encodes text as UTF-8.- Each row is written with
write()and ended withnewLine(). - Closing the writer flushes the last block, so all 501 lines are in the file.
getLast()(Java 21) reads the final line from the list.
6. Example: Counting Writes to the Destination
A small Writer subclass counts how many times text reaches the destination, first without and then with a 4,096-character buffer.
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
public class WriterCallCounter {
// Counts how often text reaches the destination
static class CountingWriter extends Writer {
int calls;
@Override public void write(char[] cbuf, int off, int len) { calls++; }
@Override public void flush() { }
@Override public void close() { }
}
public static void main(String[] args) throws IOException {
CountingWriter direct = new CountingWriter();
for (int i = 0; i < 2000; i++) {
direct.write("row " + i + "\n");
}
System.out.println("Unbuffered: " + direct.calls + " writes");
CountingWriter target = new CountingWriter();
try (Writer out = new BufferedWriter(target, 4096)) {
for (int i = 0; i < 2000; i++) {
out.write("row " + i + "\n");
}
}
System.out.println("Buffered: " + target.calls + " writes");
}
}
Unbuffered: 2000 writes Buffered: 5 writes
How the code works
- Without buffering, each of the 2,000
write()calls reaches the destination. - With buffering, text is collected and handed over only when the buffer fills and when the writer is closed: 5 calls in this run.
7. Common Mistakes and Best Practices
- Not closing or flushing. The last block of text stays in memory and is lost.
- Using
"\n"when the platform separator is required.newLine()follows the operating system. - Flushing after every line. That defeats the buffer; flush only when the data must be visible.
- Buffering a writer that is already buffered. One buffer is enough.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.1 | BufferedWriter with newLine(). |
| Java 7 and 8 | Files.newBufferedWriter(), with a UTF-8 default from Java 8. |
| Java 21 | Sequenced collections add getLast(), used in the example. |
| Java 25 | No API changes. |
9. Summary
BufferedWritercollects text and writes it in large blocks.newLine()writes the platform line separator.- Buffered text is written when the buffer fills, on
flush()and onclose(). - Use
Files.newBufferedWriter()and try-with-resources.