Java BufferedWriter
What BufferedWriter Does
java.io.BufferedWriter is the writing counterpart of BufferedReader. It wraps another Writer and collects the text you write in an in-memory buffer (8,192 characters by default). Only when the buffer is full, or when you call flush() or close(), does it pass the collected text to the underlying writer in one large chunk. It also adds a newLine() method that writes the platform's line separator.
Writer target = new FileWriter("report.txt", StandardCharsets.UTF_8); // writes characters to a file
BufferedWriter out = new BufferedWriter(target); // adds buffering and newLine()
Like all java.io decorators, it doesn't know or care where the text finally goes — a file, a network socket, the console or a StringWriter — so the same writing code works for all of them.
Why Buffering Matters for Writing
Each write that reaches the operating system has a fixed cost. Programs that produce output piece by piece — a few characters for every row, every field, every line — would make an enormous number of such calls without a buffer. The program below counts how many writes actually reach the file writer.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class CountW {
static class CountingWriter extends FilterWriter {
int calls = 0;
CountingWriter(Writer out) { super(out); }
@Override public void write(int c) throws IOException { calls++; super.write(c); }
@Override public void write(char[] buf, int off, int len) throws IOException { calls++; super.write(buf, off, len); }
@Override public void write(String s, int off, int len) throws IOException { calls++; super.write(s, off, len); }
}
public static void main(String[] args) throws IOException {
CountingWriter direct = new CountingWriter(new FileWriter("direct.txt", StandardCharsets.UTF_8));
for (int i = 0; i < 10_000; i++) {
direct.write("row " + i);
direct.write('\n');
}
direct.close();
System.out.println("unbuffered: " + direct.calls + " write calls on the file writer");
CountingWriter target = new CountingWriter(new FileWriter("buffered.txt", StandardCharsets.UTF_8));
try (BufferedWriter out = new BufferedWriter(target)) {
for (int i = 0; i < 10_000; i++) {
out.write("row " + i);
out.newLine();
}
}
System.out.println("buffered: " + target.calls + " write calls on the file writer");
System.out.println("same content: " + Files.mismatch(Path.of("direct.txt"), Path.of("buffered.txt")));
}
}
Output (on Linux or macOS):
unbuffered: 20000 write calls on the file writer
buffered: 11 write calls on the file writer
same content: -1
CountingWriterextendsFilterWriter, which forwards every call to the writer it wraps, and counts the calls.- Writing directly produces 20,000 calls: one for each row's text and one for each newline.
- With a
BufferedWriterin between, the same 10,000 lines reach the file writer in just 11 large chunks. Files.mismatch(Java 12+) compares two files and returns the position of the first differing byte, or-1if they're identical, proving that buffering changes only how the data is written, not what is written. (On Windows,newLine()writes\r\n, so the files would differ there.)
Creating a BufferedWriter
// 1. Recommended for files: Files.newBufferedWriter (UTF-8, creates or truncates by default)
BufferedWriter a = Files.newBufferedWriter(Path.of("report.txt"));
BufferedWriter b = Files.newBufferedWriter(Path.of("visits.log"), StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
// 2. Wrapping a FileWriter (charset constructors since Java 11; true = append)
BufferedWriter c = new BufferedWriter(new FileWriter("report.txt", StandardCharsets.UTF_8));
BufferedWriter d = new BufferedWriter(new FileWriter("visits.log", StandardCharsets.UTF_8, true));
// 3. Wrapping any OutputStream (console, socket, HTTP response)
BufferedWriter e = new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
// 4. Writing into memory
StringWriter sw = new StringWriter();
BufferedWriter f = new BufferedWriter(sw);
Files.newBufferedWriteris the most convenient choice for files, and it accepts open options (CREATE,APPEND,CREATE_NEW, ...) described in the Write Files lesson.new FileWriter(name)without a charset uses the platform default encoding, which was not UTF-8 everywhere before Java 18. Pass a charset explicitly.OutputStreamWriterconverts characters to bytes using a charset, letting aBufferedWriterwrite text to any byte stream.- Closing the
BufferedWriterflushes it and closes everything it wraps.
Writing Methods
import java.io.*;
import java.nio.file.*;
public class W1 {
public static void main(String[] args) throws IOException {
Path file = Path.of("letter.txt");
try (BufferedWriter w = Files.newBufferedWriter(file)) {
w.write("Dear Asha,");
w.newLine();
w.write(new char[] {'T', 'h', 'a', 'n', 'k', 's'});
w.write(' ');
w.write("for joining the Java batch. See you soon.", 0, 26);
w.write('!');
w.newLine();
w.append("Fee: ").append(String.valueOf(4999)).append(" INR");
w.newLine();
}
System.out.print(Files.readString(file));
}
}
Output:
Dear Asha,
Thanks for joining the Java batch!
Fee: 4999 INR
| Method | Writes |
|---|---|
write(String s) | The whole string |
write(String s, int off, int len) | len characters of s starting at index off — here the first 26 characters, for joining the Java batch |
write(char[] buf) / write(char[] buf, int off, int len) | Characters from an array |
write(int c) | One character whose code is c |
newLine() | The platform line separator (\n or \r\n) |
append(CharSequence) / append(char) | Same as write, but returns the writer, so calls can be chained |
A frequent surprise: write(int) writes a character, not a number. w.write(65) writes A (character code 65), not 65. To write a number as text, convert it first, as the example does with String.valueOf(4999). BufferedWriter has no print or printf methods; for formatted output, wrap it in a PrintWriter (Write Files lesson).
flush and close
import java.io.*;
import java.nio.file.*;
public class Flush {
public static void main(String[] args) throws IOException {
Path progress = Path.of("progress.log");
try (BufferedWriter w = Files.newBufferedWriter(progress)) {
w.write("step 1 done");
w.newLine();
System.out.println("before flush, file has " + Files.size(progress) + " bytes");
w.flush();
System.out.println("after flush, file has " + Files.size(progress) + " bytes");
w.write("step 2 done");
w.newLine();
}
System.out.println("after close, file has " + Files.size(progress) + " bytes");
try {
BufferedWriter w = Files.newBufferedWriter(Path.of("closed.txt"));
w.close();
w.write("too late");
} catch (IOException e) {
System.out.println("write after close: " + e.getMessage());
}
}
}
Output (on Linux or macOS):
before flush, file has 0 bytes
after flush, file has 12 bytes
after close, file has 24 bytes
write after close: Stream closed
- After the first
writeandnewLine, the 12 characters are only in the buffer; the file is still empty. flush()sends everything in the buffer to the underlying writer, and down to the operating system. The writer stays open for more output.close()flushes the remaining text and then closes the writer and the file. try-with-resources calls it automatically.- After closing, any further
writethrowsIOException: Stream closed. Callingclose()again is harmless.
When to call flush() yourself:
- Long-running writers whose output someone reads live — a progress log, or a line-based network protocol where the other side waits for your message before replying. Without
flush(), the data could sit in the buffer for a long time. - Before handing the underlying stream to other code that writes to it directly, so the output appears in the right order.
Don't flush after every line in a large export: that brings back the many small writes that buffering was meant to avoid. For most file writing, closing at the end is all you need.
Appending to a File
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
public class Append {
static void log(String line) throws IOException {
try (BufferedWriter w = Files.newBufferedWriter(Path.of("visits.log"), CREATE, APPEND)) {
w.write(line);
w.newLine();
}
}
public static void main(String[] args) throws IOException {
log("GET /java/lesson-141");
log("GET /java/lesson-142");
try (BufferedWriter w = new BufferedWriter(new FileWriter("visits.log", StandardCharsets.UTF_8, true))) {
w.write("GET /django/lesson-1");
w.newLine();
}
System.out.print(Files.readString(Path.of("visits.log")));
}
}
Output (on the first run):
GET /java/lesson-141
GET /java/lesson-142
GET /django/lesson-1
Both styles append instead of replacing:
Files.newBufferedWriter(path, CREATE, APPEND)— create the file if needed, then write at the end.new FileWriter(name, charset, true)— thetrueargument means append. Without it,FileWritertruncates the file, just likeFiles.newBufferedWriterwithout options.
Forgetting the append flag is a common way to lose log data: each run silently erases the previous content.
Errors While Writing
If an IOException occurs in the middle of writing — the disk fills up, a network drive disconnects — the exception propagates out of the write, flush or close call. Because of buffering, the failure may only surface later than the write that caused it, often in close(). Two practical consequences:
- Don't swallow exceptions from
close(). try-with-resources propagates them (or adds them as suppressed exceptions), which is one more reason to use it. - A failed write can leave a partially written file. For files that must be all-or-nothing, write to a temporary file and move it into place afterwards (the atomic-write pattern in the Write Files lesson).
Practical Example: Generating a Sitemap
Search engines discover a website's pages through sitemap.xml. Blogs and tutorial sites usually generate it from their list of pages, which may number in the thousands — a natural fit for a BufferedWriter, because the file is built line by line.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.LocalDate;
import java.util.List;
public class Sitemap {
record Page(String path, LocalDate lastModified) { }
static String xmlEscape(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (char c : s.toCharArray()) {
switch (c) {
case '&' -> sb.append("&");
case '<' -> sb.append("<");
case '>' -> sb.append(">");
case '"' -> sb.append(""");
case '\'' -> sb.append("'");
default -> sb.append(c);
}
}
return sb.toString();
}
static int writeSitemap(Path target, String baseUrl, List<Page> pages) throws IOException {
int count = 0;
try (BufferedWriter w = Files.newBufferedWriter(target, StandardCharsets.UTF_8)) {
w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
w.newLine();
w.write("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
w.newLine();
for (Page p : pages) {
w.write(" <url><loc>" + xmlEscape(baseUrl + p.path()) + "</loc>"
+ "<lastmod>" + p.lastModified() + "</lastmod></url>");
w.newLine();
count++;
}
w.write("</urlset>");
w.newLine();
}
return count;
}
public static void main(String[] args) throws IOException {
List<Page> pages = List.of(
new Page("/java/file-basics", LocalDate.of(2026, 11, 15)),
new Page("/java/read-files", LocalDate.of(2026, 11, 15)),
new Page("/search?q=java&level=beginner", LocalDate.of(2026, 11, 10)));
int n = writeSitemap(Path.of("sitemap.xml"), "https://example.com", pages);
System.out.println(n + " URLs written");
System.out.print(Files.readString(Path.of("sitemap.xml")));
}
}
Output:
3 URLs written
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://example.com/java/file-basics</loc><lastmod>2026-11-15</lastmod></url>
<url><loc>https://example.com/java/read-files</loc><lastmod>2026-11-15</lastmod></url>
<url><loc>https://example.com/search?q=java&level=beginner</loc><lastmod>2026-11-10</lastmod></url>
</urlset>
How it works:
- The XML declaration says
UTF-8, and the writer is created withStandardCharsets.UTF_8. The declared and actual encodings must match, or XML parsers will misread non-ASCII characters. xmlEscapereplaces the five characters that have special meaning in XML. The third URL contains&, which must be written as&; an unescaped&makes the whole file invalid XML, and search engines would reject it.StringBuilderwith an initial capacity avoids repeated resizing.LocalDate.toString()produces2026-11-15, the ISO-8601 format the sitemap protocol requires for<lastmod>.- Each
<url>entry is written and followed bynewLine(); the buffer collects them and writes large blocks to disk, so the cost per page stays tiny even for tens of thousands of pages. - try-with-resources writes the closing
</urlset>and guarantees the buffer is flushed. A sitemap missing its last lines because the writer wasn't closed is an invalid file. - The method returns the number of URLs, which the caller can log or check against the sitemap protocol's limit of 50,000 URLs per file.
For complex XML, an XML library (such as the JDK's XMLStreamWriter) handles escaping automatically. For simple, well-defined formats like this one, a BufferedWriter with careful escaping is fast, dependency-free and easy to follow.