Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Java

Convertire da windows-1250 a UTF-8 e gestire gli errori di decodifica

Converti i byte da windows-1250 a UTF-8 decodificandoli in caratteri Unicode e poi ricodificandoli. Decidi come deve reagire il decodificatore a ogni tipo di errore.

Versione: Java SE 21

Sintassi

Java SE 21 — java.nio.charset (buffers in java.nio)
Charset.forName(String charsetName) -> Charset
Charset.forName(String charsetName, Charset fallback) -> Charset
charset.newDecoder() -> CharsetDecoder
charset.newEncoder() -> CharsetEncoder
decoder.onMalformedInput(CodingErrorAction action) -> CharsetDecoder
decoder.onUnmappableCharacter(CodingErrorAction action) -> CharsetDecoder
decoder.decode(ByteBuffer in) -> CharBuffer; throws CharacterCodingException
decoder.decode(ByteBuffer in, CharBuffer out, boolean endOfInput) -> CoderResult
encoder.encode(CharBuffer in) -> ByteBuffer; throws CharacterCodingException
encoder.encode(CharBuffer in, ByteBuffer out, boolean endOfInput) -> CoderResult

In Java SE 21, Charset.forName(String) del pacchetto java.nio.charset cerca una codifica per nome canonico o alias. Un nome non valido causa IllegalCharsetNameException; una codifica non supportata causa UnsupportedCharsetException. L’overload forName(String, Charset), disponibile da Java 18, restituisce in entrambi i casi il valore di ripiego, che può essere null. Entrambi gli overload rifiutano un nome null con IllegalArgumentException.

Chiama newDecoder() sulla codifica di origine per leggere i byte come caratteri Unicode e newEncoder() su quella di destinazione per scrivere nuovi byte. Oracle JDK 21 supporta windows-1250, ma Java SE non lo richiede; StandardCharsets.UTF_8 è invece garantito. Se il set di caratteri non consente la codifica in byte, newEncoder() lancia UnsupportedOperationException. Decodificatori e codificatori mantengono uno stato e non sono sicuri per l’uso concorrente.

onMalformedInput(action) gestisce le sequenze di byte che violano le regole della codifica; onUnmappableCharacter(action) gestisce quelle ben formate ma prive di una corrispondenza Unicode. Entrambi i metodi modificano e restituiscono lo stesso decodificatore. REPORT, l’azione predefinita, segnala l’errore; REPLACE inserisce il testo sostitutivo (inizialmente U+FFFD); IGNORE scarta l’input errato. Sostituire o scartare comporta una perdita di informazioni. Usa REPORT quando gli errori non devono passare inosservati, ma non considerarlo una prova di aver scelto la codifica di origine corretta. La scorciatoia Charset.decode(...) effettua una sostituzione per entrambi i tipi di errore.

CharsetDecoder.decode(ByteBuffer) e CharsetEncoder.encode(CharBuffer), con un solo argomento, leggono l’input rimanente e restituiscono rispettivamente un nuovo CharBuffer o ByteBuffer. Con REPORT, un errore causa MalformedInputException o UnmappableCharacterException, entrambe sottoclassi di CharacterCodingException. Per elaborare a blocchi, usa l’overload con buffer di uscita e flag endOfInput: controlla CoderResult, conserva l’input non consumato e chiama flush(...) dopo l’ultimo blocco. Non chiamare la variante a un argomento mentre l’operazione è in corso.

Esempi

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;

public class CharsetDemo {
    private static CharsetDecoder decoder(Charset charset, CodingErrorAction action) {
        return charset.newDecoder()
                .onMalformedInput(action)
                .onUnmappableCharacter(action);
    }

    public static void main(String[] args) throws java.nio.charset.CharacterCodingException {
        Charset source = Charset.forName("windows-1250");
        Charset utf8 = StandardCharsets.UTF_8;

        byte[] legacy = {(byte) 0xA5};
        CharBuffer text = decoder(source, CodingErrorAction.REPORT)
                .decode(ByteBuffer.wrap(legacy));
        ByteBuffer encoded = utf8.newEncoder().encode(text);
        byte[] output = new byte[encoded.remaining()];
        encoded.get(output);
        System.out.println("windows-1250 -> UTF-8: "
                + HexFormat.ofDelimiter(" ").withUpperCase().formatHex(output));

        byte[] truncatedUtf8 = {(byte) 0xC3};
        try {
            decoder(utf8, CodingErrorAction.REPORT).decode(ByteBuffer.wrap(truncatedUtf8));
            throw new AssertionError("Expected malformed UTF-8");
        } catch (MalformedInputException expected) {
            System.out.println("REPORT: MalformedInputException");
        }

        CharBuffer repaired = decoder(utf8, CodingErrorAction.REPLACE)
                .decode(ByteBuffer.wrap(truncatedUtf8));
        System.out.printf("REPLACE: U+%04X%n", Character.codePointAt(repaired, 0));
    }
}

Risultato

windows-1250 -> UTF-8: C4 84
REPORT: MalformedInputException
REPLACE: U+FFFD

Il byte `A5` in windows-1250 rappresenta `U+0104`, che in UTF-8 si scrive `C4 84`. In una prova separata, il solo byte `C3` è l’inizio di una sequenza UTF-8 incompleta: `REPORT` lancia un’eccezione, mentre `REPLACE` produce `U+FFFD`. L’output esadecimale non dipende da come il terminale visualizza Unicode.

Lezioni correlate

  • Java · Lezione 51 · Avanzato · Versione: 2

Fonti