CharsetDecoder Malformed Input Actions

Decode bytes that may be truncated UTF-8 with an explicit CharsetDecoder: REPORT rejects malformed input with an exception, REPLACE substitutes U+FFFD.

JavaResilience

Code

snippet
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 BrokenByteFixer {

    public static void main(String[] args) throws CharacterCodingException {
        // 0xC3 后面本应跟一个连续字节,这里被截断 → 非法 UTF-8 序列
        ByteBuffer truncated = ByteBuffer.wrap(new byte[] {'O', 'K', (byte) 0xC3});

        // 两种动作(actions)控制非法输入的处理策略
        CharsetDecoder strict = StandardCharsets.UTF_8.newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT);
        try {
            strict.decode(truncated);
        } catch (CharacterCodingException e) {
            System.out.println("REPORT: " + e.getClass().getSimpleName());
        }

        // REPLACE:把非法序列替换成 U+FFFD,输出仍然可用
        truncated.rewind();
        CharsetDecoder lenient = StandardCharsets.UTF_8.newDecoder()
                .onMalformedInput(CodingErrorAction.REPLACE);
        System.out.println("REPLACE: [" + lenient.decode(truncated) + "]");
    }
}

How it works

Count the class BrokenByteFixer as the entire surface area of CharsetDecoder Malformed Input Actions.

Putting it to use

The demo output is labeled (REPORT:, REPLACE: [), so each line traces straight back to the statement that printed it.

Core lines

ByteBuffer truncated = ByteBuffer.wrap(new byte[] {'O', 'K', (byte) 0xC3});
CharsetDecoder lenient = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE);
CharsetDecoder strict = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT);

Interactive Tools for This Topic

FAQ

What does CharsetDecoder Malformed Input Actions print when run?
Execute the whole file; each printed line is prefixed with a label like `REPORT:`, `REPLACE: [`.