Object Stream Opened In Append Mode

ID

java.files_opened_append_mode_objectoutputstream

Severity

critical

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

reliability

Description

Reports new ObjectOutputStream(new FileOutputStream(file, true)): an ObjectOutputStream built directly on top of a FileOutputStream opened in append mode.

An anonymous subclass that overrides writeStreamHeader() is not reported. Suppressing the header that way is the documented fix for this very problem — it is what makes appending to an existing stream safe — so flagging it would report the remedy as the defect.

Rationale

ObjectOutputStream’s constructor writes a stream header as the first bytes of the underlying stream. Opening the target file in append mode and handing it straight to `ObjectOutputStream writes that header into the middle of a file that may already hold a serialized stream with its own header. The result is a file ObjectInputStream cannot read back: it throws StreamCorruptedException the moment it hits the unexpected second header.

// Bad -- writes a second header into the middle of the file
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(journal, true))) {
    out.writeObject(entry);
}

Remediation

If the file may already contain a serialized stream, open it once, keep the ObjectOutputStream open for the life of that stream, and append further objects to the same stream instead of reopening the file. If each call is meant to (re)write a fresh, self-contained stream, drop the append flag.

// Good -- a fresh stream with its own single header
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(journal, false))) {
    out.writeObject(entry);
}

© 2026 Xygeni. All rights reserved