次のコードを検討してください。
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 を使用する)の 2 番目の呼び出しが成功するのはなぜですか? このエンコーディングでは入力が適切な文字ではないため、エラーがスローされると予想されます。この動作を義務付ける Java API または JLS の場所はどこですか?