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

Append Mode: Adding to Existing Files with FileWriter

Learn how to use FileWriter's append mode to add content to existing files without overwriting them.

Append Mode: Adding to Existing Files with FileWriter

You'll learn how to add new content to the end of existing files without erasing what's already there.

The Problem with Default FileWriter Behavior

By default, when you create a FileWriter with just a file path, it overwrites the entire file. Any existing content is wiped out and replaced with your new data. Think of it like erasing a whiteboard before writing on it—sometimes useful, but not when you want to keep what's already there.

Enabling Append Mode

To add content to the end of an existing file (or create a new one if it doesn't exist), use the two-argument FileWriter constructor:

FileWriter writer = new FileWriter("log.txt", true);

The second parameter is a boolean flag:

  • true: Append mode—adds content to the end of the file
  • false (or omitted): Overwrite mode—replaces the entire file

How It Works

When append mode is enabled, the writer positions itself at the end of the file before writing. It's like opening a journal and flipping to the last written page—you continue from there rather than starting over.

try (FileWriter writer = new FileWriter("notes.txt", true)) {
    writer.write("New entry at the end.\n");
} catch (IOException e) {
    e.printStackTrace();
}

Each time you run this code, it adds another line to notes.txt without removing previous entries.

Common Use Cases

Append mode is ideal for log files, transaction records, or any scenario where you need to preserve history while adding new data.

Key Takeaway: Use new FileWriter(path, true) to append content to existing files; the second boolean parameter controls whether you add to or replace the file's contents.