WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Java

Ein-/Ausgabe und Serialisierung in Java

Ein-/Ausgabe und Serialisierung in Java: Java I/O umfasst Bytes über InputStream/OutputStream, Zeichen über Reader/Writer mit Charset, NIO-Dateien über Path/Files und Serializable-Objektgraphen über ObjectOutput und ObjectInput.

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

Syntax

io

Java I/O umfasst Bytes über InputStream/OutputStream, Zeichen über Reader/Writer mit Charset, NIO-Dateien über Path/Files und Serializable-Objektgraphen über ObjectOutput und ObjectInput.

Nutze try-with-resources und Pufferung, explizites StandardCharsets.UTF_8 für Protokolle und eine stabile serialVersionUID nur für kontrollierte, vertrauenswürdige Datentypen.

In Java 21 ist der Standard-Charset UTF-8; implementierungsspezifische Konfiguration wie file.encoding=COMPAT kann den Plattform-Charset wiederherstellen. Fremde Deserialisierung ist gefährlich.

Eine abweichende serialVersionUID verursacht InvalidClassException, transient lässt ein Feld aus, Files.lines/list/walk brauchen close und readAllBytes kann Speicher erschöpfen.

Die Serialisierung stellt name und count wieder her, aber transient secret wird null; UTF-8 codiert ż in genau zwei Bytes.

Beispiele

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);
    }
}

Ergebnis

Ada:7:null
2

Die Serialisierung stellt name und count wieder her, aber transient secret wird null; UTF-8 codiert ż in genau zwei Bytes.

Quellen