编程语言
首页 > 编程语言> > java – 为什么US-ASCII编码接受非US-ASCII字符?

java – 为什么US-ASCII编码接受非US-ASCII字符?

作者:互联网

请考虑以下代码:

public class ReadingTest {

    public void readAndPrint(String usingEncoding) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[]{(byte) 0xC2, (byte) 0xB5}); // 'micro' sign UTF-8 representation
        InputStreamReader isr = new InputStreamReader(bais, usingEncoding);
        char[] cbuf = new char[2];
        isr.read(cbuf);
        System.out.println(cbuf[0]+" "+(int) cbuf[0]);
    }

    public static void main(String[] argv) throws Exception {
        ReadingTest w = new ReadingTest();
        w.readAndPrint("UTF-8");
        w.readAndPrint("US-ASCII");
    }
}

观察到的输出:

µ 181
? 65533

为什么readAndPrint()(使用US-ASCII的那个)的第二次调用成功?我希望它会抛出一个错误,因为输入不是这个编码中的正确字符. Java API或JLS中强制执行此行为的位置是什么?

解决方法:

在输入流中查找不可解码字节时的默认操作是将其替换为Unicode字符U+FFFD REPLACEMENT CHARACTER.

如果要更改它,可以传递配置了不同CodingErrorActionCharacterDecoder to the InputStreamReader

CharsetDecoder decoder = Charset.forName(usingEncoding).newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
InputStreamReader isr = new InputStreamReader(bais, decoder);

标签:ascii,java,encoding,utf-8,non-ascii-characters
来源: https://codeday.me/bug/20190715/1471789.html