Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Java

I/O e serializzazione in Java

I/O e serializzazione in Java: Java I/O comprende byte InputStream/OutputStream, caratteri Reader/Writer con Charset, file NIO tramite Path/Files e grafi Serializable tramite ObjectOutput e ObjectInput.

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

Sintassi

io

Java I/O comprende byte InputStream/OutputStream, caratteri Reader/Writer con Charset, file NIO tramite Path/Files e grafi Serializable tramite ObjectOutput e ObjectInput.

Usa try-with-resources e buffering, StandardCharsets.UTF_8 esplicito per i protocolli e serialVersionUID stabile solo per tipi di dati controllati e fidati.

In Java 21 il Charset predefinito è UTF-8; una configurazione specifica dell’implementazione come file.encoding=COMPAT può ripristinare quello di piattaforma. Deserializzare dati non fidati è pericoloso.

Un serialVersionUID diverso causa InvalidClassException, transient omette un campo, Files.lines/list/walk richiedono close e readAllBytes può esaurire la memoria.

La serializzazione ripristina name e count, ma il campo transient secret diventa null; UTF-8 codifica ż in esattamente due byte.

Esempi

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

Risultato

Ada:7:null
2

La serializzazione ripristina name e count, ma il campo transient secret diventa null; UTF-8 codifica ż in esattamente due byte.

Fonti