考虑以下代码:
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 中强制执行此行为的位置是什么?