01 / 20

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.

Java

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.

Java Program write Writer Object bytes File on disk

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.

Package
java.io.FileWriter
Extends
OutputStreamWriter → Writer
Purpose
Write characters to a text file

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.

Your Code write("Hi") BufferedWriter H i _ _ _ _ internal buffer (8192 chars) flush FileWriter → disk

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.

try (BufferedWriter bw = new BufferedWriter( new FileWriter("output.txt"))) { bw.write("Hello, file!"); bw.newLine(); bw.write("Second line."); } catch (IOException e) { e.printStackTrace(); }

Key Methods to Know

1
write(String s): Writes the string to the buffer (or directly to file if using FileWriter alone).
2
write(char[] cbuf, int off, int len): Writes a portion of a character array.
3
newLine(): Writes the platform-specific line separator. Only available on BufferedWriter.
4
flush(): Forces buffered data to be written to the underlying stream immediately.
5
close(): Flushes, then releases the file resource. Called automatically with try-with-resources.

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:

Overwrite Mode
new FileWriter("file.txt")
Creates a new file or erases existing content.
Append Mode
new FileWriter("file.txt", true)
Creates a new file or adds to the end of existing content.

How to Write a File: Step by Step

1
Import java.io.*: You need IOException, FileWriter, and BufferedWriter.
2
Open a try-with-resources block: Declare your BufferedWriter wrapping a FileWriter in the parentheses.
3
Write your data: Use write() for text and newLine() for line breaks.
4
Handle exceptions: Catch IOException in the catch block and handle or log it.
5
Let close() happen automatically: The try-with-resources flushes and closes for you.

Example 1: Basic File Write

import java.io.*; public class WriteDemo { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter( new FileWriter("greeting.txt"))) { bw.write("Hello, World!"); bw.newLine(); bw.write("Welcome to Java I/O."); } catch (IOException e) { e.printStackTrace(); } } }

Example 2: Append Mode

try (BufferedWriter bw = new BufferedWriter( new FileWriter("log.txt", true))) { // true = append bw.write("[INFO] User logged in"); bw.newLine(); } catch (IOException e) { e.printStackTrace(); }

Example 3: Writing in a Loop

String[] names = {"Alice", "Bob", "Carol"}; try (BufferedWriter bw = new BufferedWriter( new FileWriter("names.txt"))) { for (String name : names) { bw.write(name); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); }

Why Buffering Matters

FileWriter alone (1000 writes) 1000 1000 disk operations BufferedWriter (1000 writes) ~1 ~1 disk operation Buffer collects characters in memory, then writes them all at once on flush/close.

Common Mistakes

✕ Not Closing the Writer
If you forget close() and don't use try-with-resources, the buffer may never flush and your file ends up empty or incomplete.
✕ Overwriting by Accident
Using new FileWriter("file") without the true flag erases the file's previous contents every time.
✕ Using "\n" Instead of newLine()
Hardcoding "\n" works on Linux/Mac but produces wrong line endings on Windows. Use newLine() for portability.

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

After both blocks run, what does scores.txt contain?