Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CharsetDecoder — decoding bytes with error control

CharsetDecoder converts bytes in a selected charset into Unicode characters. It independently configures handling of malformed and unmappable sequences: reporting errors, replacing input, or ignoring input.

Version: Documentation target: Java SE 21; repository and production runtime versions are not attested.

Syntax

CharsetDecoder decoder = charset.newDecoder()
    .onMalformedInput(CodingErrorAction.REPORT)
    .onUnmappableCharacter(CodingErrorAction.REPORT);
CharBuffer text = decoder.decode(input);

java.nio.charset.CharsetDecoder converts bytes into Unicode characters; create it through charset.newDecoder(). This entry targets Java SE 21; repository and production runtime versions are not attested.

CharsetDecoder.onMalformedInput controls sequences that are illegal in the charset. CharsetDecoder.onUnmappableCharacter controls legal sequences without a mapping to Unicode characters. Both methods accept CodingErrorAction: REPORT reports an error, REPLACE substitutes for erroneous input, and IGNORE drops it. Replacement and omission lose information.

CharsetDecoder.decode(ByteBuffer) returns a CharBuffer; with REPORT, errors are thrown as exceptions in the CharacterCodingException family. The overload decode(ByteBuffer, CharBuffer, boolean) supports incremental processing and returns a CoderResult that must be handled.

The example uses 0xFF, an invalid UTF-8 byte. It first reports the error, then replaces the byte with ?. This demonstrates malformed input, not an unmappable sequence; the second policy remains REPORT.

Examples

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

public class DecoderDemo {
    public static void main(String[] args) throws CharacterCodingException {
        byte[] bytes = {65, (byte) 0xFF, 66};
        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
            .onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);

        try {
            decoder.decode(ByteBuffer.wrap(bytes));
        } catch (CharacterCodingException ex) {
            System.out.println("REPORT: " + ex.getClass().getSimpleName());
        }

        decoder.reset();
        decoder.onMalformedInput(CodingErrorAction.REPLACE)
            .replaceWith("?");
        System.out.println("REPLACE: " + decoder.decode(ByteBuffer.wrap(bytes)));
    }
}

Result

REPORT: MalformedInputException
REPLACE: A?B

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