【发布时间】:2011-06-20 15:55:54
【问题描述】:
考虑以下代码:
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 中的什么地方要求这种行为?
【问题讨论】:
标签: java encoding utf-8 ascii non-ascii-characters