## Why is this an issue?

An `ObjectOutputStream` writes primitive data types and graphs of Java objects to an `OutputStream`. The objects can be read (reconstituted) using an `ObjectInputStream`.

When `ObjectOutputStream` is used with files opened in append mode, it can cause data corruption and unexpected behavior. This is because when `ObjectOutputStream` is created, it writes metadata to the output stream, which can conflict with the existing metadata when the file is opened in append mode. This can lead to errors and data loss.

When used with serialization, an `ObjectOutputStream` first writes the serialization stream header. This header should appear once per file at the beginning. When you’re trying to read your object(s) back from the file, only the first one will be read successfully, and a `StreamCorruptedException` will be thrown after that.

## How to fix it

Open the file to use the default action (writes stream header).

### Code examples

#### Noncompliant code example

    FileOutputStream fos = new FileOutputStream(fileName , true);  // fos opened in append mode
    ObjectOutputStream out = new ObjectOutputStream(fos);  // Noncompliant

#### Compliant solution

    FileOutputStream fos = new FileOutputStream(fileName);
    ObjectOutputStream out = new ObjectOutputStream(fos);

## Resources

### Articles & blog posts

- JBoss - AppendingObjectOutputStream

### Documentation

- Oracle SE 20 - ObjectOutputStream