← 中文资源

简体中文版本

CharsetDecoder 非法字节处理

被截断的 UTF-8 序列交给 CharsetDecoder:REPORT 直接抛 MalformedInputException 快速失败,REPLACE 用 U+FFFD 替换后照常输出。

阅读英文原文

实现说明

CharsetDecoder 非法字节处理以类 BrokenByteFixer为骨架。

使用要点

  • 直接运行文件,输出会带上标签,比如 REPORT:、REPLACE: [——输出的每一行都能指回产生它的那次调用。

常见问题

运行「CharsetDecoder 非法字节处理」会打印什么?

整个文件跑完,输出行以 REPORT:、REPLACE: [ 这类前缀开头。

核心语句

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

代码示例

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) + "]");
    }
}