FileWriter &
BufferedWriter
Learn to write text files in Java using FileWriter and BufferedWriter: how they work, when to use each, and best practices for efficient file output.
What Is File I/O?
File I/O (Input/Output) is how your Java program reads from and writes to files on disk. Without it, all your data disappears when the program ends. File I/O lets you persist data between runs.
Meet FileWriter
FileWriter is a class in java.io that converts characters into bytes and writes them directly to a file. It is the simplest way to write text in Java.
Meet BufferedWriter
BufferedWriter wraps around a Writer (like FileWriter) and adds an internal buffer. Instead of writing every character immediately, it collects them and writes in larger chunks: far more efficient.
The Core Writing Pattern
Java's recommended pattern wraps FileWriter inside BufferedWriter inside a try-with-resources block. This ensures automatic closing even if an exception occurs.
Key Methods to Know
FileWriter vs BufferedWriter
| FileWriter | BufferedWriter | |
|---|---|---|
| Buffered? | No | Yes (8192 chars) |
| newLine() method? | No | Yes |
| Performance | Slower for many writes | Faster (batches writes) |
| Used alone? | Can be, for simple tasks | Always wraps another Writer |
| Typical usage | Quick, tiny files | Any real application |
Constructor Options
FileWriter has two important constructors that control whether you overwrite or append to a file:
How to Write a File: Step by Step
Example 1: Basic File Write
Example 2: Append Mode
Example 3: Writing in a Loop
Why Buffering Matters
Common Mistakes
Summary Cheat Sheet
| Concept | Detail |
|---|---|
| Import | java.io.* |
| Create writer | new BufferedWriter(new FileWriter(...)) |
| Write text | bw.write("text") |
| New line | bw.newLine() |
| Append mode | new FileWriter("file", true) |
| Resource mgmt | try-with-resources (auto close) |
| Exception | catch IOException |
Question 1 of 5
What is the primary advantage of wrapping FileWriter in a BufferedWriter?
Question 2 of 5
Which constructor call opens a file in append mode?
Question 3 of 5
What happens if you never close a BufferedWriter and don't use try-with-resources?
Question 4 of 5
Which method is available on BufferedWriter but not on FileWriter?
Question 5 of 5
Consider this code:
BufferedWriter bw = new BufferedWriter(
new FileWriter("scores.txt"));
bw.write("Alice: 95");
bw.newLine();
bw.write("Bob: 88");
bw.close();
BufferedWriter bw2 = new BufferedWriter(
new FileWriter("scores.txt"));
bw2.write("Carol: 91");
bw2.close();
After both blocks run, what does scores.txt contain?