Consider the following code:
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
为什么使用 US-ASCII 的第二个 readAndPrint()
调用成功了呢?我本以为它会报错,因为输入不是这种编码中的合适字符。Java API 或 JLS 中指定了这种行为的地方在哪里?
InputStreamReader
的代码,因为它不是我的 -org.apache.tools.ant.taskdefs.SQLExec.Transaction.runTransaction(PrintStream)
。我很惊讶地发现Ant的<sql>
任务的encoding
属性不能防止输入格式不正确。 - Grzegorz Oledzki