Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ObjectOutputStream — writing Java objects

ObjectOutputStream writes objects as a Java serialization byte stream. Learn writeObject, the distinction between flush and close, and automatic closure with try-with-resources.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ObjectOutputStream out = new ObjectOutputStream(outputStream);
out.writeObject(object);
out.flush();
out.close();

ObjectOutputStream wraps an OutputStream and writes Java's binary serialization format, not text. Its constructor writes a header. ObjectOutputStream.writeObject(obj) writes an object graph; ordinary objects must implement Serializable. Shared references and cycles are preserved through handles rather than repeatedly copying an object.

Default serialization includes non-static fields without transient. A non-serializable object that must be written causes NotSerializableException. Reading with ObjectInputStream requires compatible classes. Explicit read operations must match the order and kind of the explicit data writes. This does not require identical field layouts: adding a field can be a compatible change under default deserialization. Deleting a field is an incompatible change: even if deserialization succeeds, an older version of the class may receive the default value for that field and be unable to honor its contract. Do not write secrets without deliberately controlling the serialized state.

ObjectOutputStream.flush() forwards buffered bytes and flushes the underlying stream; it neither closes the stream nor guarantees physical disk persistence. ObjectOutputStream.close() closes the stream and releases resources. Prefer try-with-resources, which calls close() automatically. Operations can throw IOException; after a writeObject failure, do not assume the stream remains usable.

Examples

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject("CKTIS");
            out.flush();
        }

        try (ObjectInputStream in = new ObjectInputStream(
                new ByteArrayInputStream(bytes.toByteArray()))) {
            System.out.println(in.readObject());
        }
    }
}

Result

CKTIS

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources