Java BufferedWriter Reference
›Short versionOpen if you only have a minute.
- BufferedWriter holds characters in memory and writes them in larger chunks to another Writer.
- write does not add a newline. newLine writes the platform line separator.
- Characters can sit in the buffer until flush or close. A program that never closes can lose the tail of the file.
- close flushes, then closes the wrapped writer. Further write calls throw IOException.
- FileWriter(path) overwrites the file. FileWriter(path, true) appends.
- PrintWriter adds print and println. It can also hide an IOException unless you ask it.
BufferedWriter collects character output in memory and writes it in larger chunks. It is useful when writing many small pieces of text.
Methods
| API | Parameters | Returns | Behavior | Watch for |
|---|---|---|---|---|
| new BufferedWriter(Writer out) | Writer destination, optional buffer size overload. | BufferedWriter. | Adds buffering around character output. | Wrapped writer controls charset and target. |
| write(String s) | String to write. | void. | Writes characters into the buffer. | Does not append a newline. |
| write(char[] cbuf, int off, int len) | Character buffer, start offset, count. | void. | Writes a selected range. | off and len must describe a valid range. |
| newLine() | None. | void. | Writes the system line separator. | Use this instead of hardcoding "\n" for portability. |
| flush() | None. | void. | Forces buffered characters to the destination. | Flushing too often reduces buffering benefits. |
| close() | None. | void. | Flushes then closes the writer chain. | Further writes throw IOException. |
Which call fits
| Option | Best for | Tradeoff |
|---|---|---|
| BufferedWriter | Repeated text writes with explicit line handling. | No printf-style formatting. |
| PrintWriter | Convenient print, println, and printf methods. | Can hide IOExceptions unless checked. |
| Files.writeString() | Writing one complete small string. | Less suitable for streaming many incremental writes. |
Examples
Write lines
java
try (BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"))) {
writer.write("first");
writer.newLine();
writer.write("second");
}Append text
java
try (BufferedWriter writer = new BufferedWriter(new FileWriter("app.log", true))) {
writer.write("Started");
writer.newLine();
}A BufferedWriter writes two lines and the method returns without flush or close. What can be missing from the file?
The last characters still sitting in the buffer. They were accepted by write and never sent to the FileWriter underneath. close() would have flushed them. Opening the same path later with new FileWriter(path) is a second surprise: that constructor truncates the file unless you pass true to append.