java – 为什么US-ASCII编码接受非US-ASCII字符?
发布时间:2020-12-15 04:53:59 所属栏目:Java 来源:网络整理
导读:请考虑以下代码: 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 I
请考虑以下代码:
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.
如果要更改它,可以传递配置了不同 CharsetDecoder decoder = Charset.forName(usingEncoding).newDecoder(); decoder.onMalformedInput(CodingErrorAction.REPORT); InputStreamReader isr = new InputStreamReader(bais,decoder); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |