Course contentsShow
← Java
Lesson 1983 of 2,87040. File I/O: Character StreamsFree lesson

Writing with write() Methods in BufferedWriter

Use write() to output strings, characters, or character arrays efficiently through the internal buffer.

Writing with write() Methods in BufferedWriter

What you'll learn: How to efficiently output text using BufferedWriter's write() methods with internal buffering.

The Core Idea

BufferedWriter doesn't directly write every character to disk immediately. Instead, it collects your output in an internal buffer (like a temporary holding area) and writes larger chunks at once. You use the write() methods to put characters into this buffer—the actual disk writes happen when the buffer fills up or when you explicitly flush() or close().

Think of it like filling a bucket with water before pouring it into a larger container. Rather than making many tiny trips (expensive), you fill the bucket first and make fewer, larger pours (efficient).

The write() Method Variants

BufferedWriter inherits and implements several write() methods from Writer:

1. write(int c) – Writes a single character (the lower 16 bits of the int):

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write('A');  // Writes the character 'A'

2. write(char[] cbuf) – Writes an entire character array:

char[] data = {'H', 'e', 'l', 'l', 'o'};
writer.write(data);  // Writes "Hello"

3. write(char[] cbuf, int off, int len) – Writes a portion of a character array:

char[] data = {'H', 'e', 'l', 'l', 'o', '!'};
writer.write(data, 0, 5);  // Writes "Hello" (5 characters starting at index 0)

4. write(String s) – Writes an entire string:

writer.write("Hello, world!");

5. write(String s, int off, int len) – Writes part of a string:

writer.write("Hello, world!", 0, 5);  // Writes "Hello"

All these methods add characters to the internal buffer—they don't immediately hit the disk, making them fast for repeated calls.

Key Takeaway: BufferedWriter's write() methods efficiently output characters, strings, or character arrays by placing them in an internal buffer first, reducing costly disk operations until the buffer is full, flushed, or closed.