Course contentsShow
← Java
Lesson 1918 of 2,87039. File I/O: Basic Byte StreamsFree lesson

FileOutputStream Constructors: Overwrite vs Append Mode

Learn the difference between default overwrite behavior and append mode using the boolean append parameter.

FileOutputStream Constructors: Overwrite vs Append Mode

You'll learn how to control whether FileOutputStream replaces existing file content or adds to the end of it.

The Default: Overwrite Mode

When you create a FileOutputStream using just a file path or File object, it overwrites any existing content in that file. Think of it like opening a blank document in a word processor—whatever was there before is gone, and you're starting fresh.

// This will ERASE existing content
FileOutputStream fos = new FileOutputStream("output.txt");

Every time you run code with this constructor, the file starts empty. This is the most common use case when you want to generate a new file from scratch.

Append Mode: Adding to Existing Content

Sometimes you want to add data to the end of a file without losing what's already there—like adding new entries to a log file. For this, use the two-parameter constructor with a boolean append flag:

// This will ADD to existing content
FileOutputStream fos = new FileOutputStream("output.txt", true);

// Explicitly overwrite (same as one-parameter version)
FileOutputStream fos2 = new FileOutputStream("output.txt", false);

When append is true, the stream positions itself at the end of the file. Any bytes you write get added after the existing content.

Real-World Analogy

Think of overwrite mode as replacing a billboard poster with a completely new one, while append mode is like stapling additional sheets to the bottom of an existing notice board.

When to Use Each

  • Overwrite (false or omit the parameter): Reports, generated files, temporary data
  • Append (true): Log files, incremental data collection, audit trails

Key Takeaway: FileOutputStream overwrites files by default; pass true as the second constructor parameter to append instead of replacing existing content.