39 lines
1.3 KiB
Plaintext
39 lines
1.3 KiB
Plaintext
== 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
|
|
|
|
[source,kotlin,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
val fos = FileOutputStream(fileName, true) // fos opened in append mode
|
|
val out = ObjectOutputStream(fos) // Noncompliant
|
|
----
|
|
|
|
|
|
==== Compliant solution
|
|
|
|
[source,kotlin,diff-id=1,diff-type=compliant]
|
|
----
|
|
val fos = FileOutputStream(fileName)
|
|
val out = ObjectOutputStream(fos)
|
|
----
|
|
|
|
|