Java BufferedWriter

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 142 of 306

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
  • CountingWriter extends FilterWriter, 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 BufferedWriter in 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 -1 if 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.newBufferedWriter is 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.
  • OutputStreamWriter converts characters to bytes using a charset, letting a BufferedWriter write text to any byte stream.
  • Closing the BufferedWriter flushes 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
MethodWrites
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 write and newLine, 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 write throws IOException: Stream closed. Calling close() 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) — the true argument means append. Without it, FileWriter truncates the file, just like Files.newBufferedWriter without 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:

  1. The XML declaration says UTF-8, and the writer is created with StandardCharsets.UTF_8. The declared and actual encodings must match, or XML parsers will misread non-ASCII characters.
  2. xmlEscape replaces 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. StringBuilder with an initial capacity avoids repeated resizing.
  3. LocalDate.toString() produces 2026-11-15, the ISO-8601 format the sitemap protocol requires for <lastmod>.
  4. Each <url> entry is written and followed by newLine(); the buffer collects them and writes large blocks to disk, so the cost per page stays tiny even for tens of thousands of pages.
  5. 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.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java BufferedWriter and get answers drawn from it.

Signed-in readers only.