Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

I/O and serialization in Java

I/O and serialization in Java: Java I/O covers InputStream/OutputStream bytes, Reader/Writer characters with Charset, NIO files through Path/Files, and Serializable object graphs through ObjectOutput and ObjectInput.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

io

Java I/O covers InputStream/OutputStream bytes, Reader/Writer characters with Charset, NIO files through Path/Files, and Serializable object graphs through ObjectOutput and ObjectInput.

Use try-with-resources and buffering, explicit StandardCharsets.UTF_8 for protocols, and a stable serialVersionUID only for controlled, trusted data types.

In Java 21 the default Charset is UTF-8; implementation-specific configuration such as file.encoding=COMPAT can restore the platform charset. Deserializing untrusted data is dangerous.

A serialVersionUID mismatch causes InvalidClassException, transient omits a field, Files.lines/list/walk require close, and readAllBytes can exhaust memory.

Serialization restores name and count, but the transient secret becomes null; UTF-8 encodes ż in exactly two bytes.

Examples

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

public class Main {
    static final class Snapshot implements Serializable {
        private static final long serialVersionUID = 1L;
        final String name;
        final int count;
        transient String secret;

        Snapshot(String name, int count, String secret) {
            this.name = name;
            this.count = count;
            this.secret = secret;
        }
    }

    public static void main(String[] args) throws Exception {
        var bytes = new ByteArrayOutputStream();
        try (var out = new ObjectOutputStream(bytes)) {
            out.writeObject(new Snapshot("Ada", 7, "token"));
        }
        Snapshot restored;
        try (var in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
            restored = (Snapshot) in.readObject();
        }
        System.out.println(restored.name + ":" + restored.count + ":" + restored.secret);
        System.out.println("ż".getBytes(StandardCharsets.UTF_8).length);
    }
}

Result

Ada:7:null
2

Serialization restores name and count, but the transient secret becomes null; UTF-8 encodes ż in exactly two bytes.

Sources