我正在阅读Java™I/O,第2版这本书,这里有以下代码:
try {
byte[] b = new byte[10];
System.in.read(b);
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}
Run Code Online (Sandbox Code Playgroud)
从书中引用:
"..没有什么可以阻止你尝试将更多数据读入数组而不是适合.如果你这样做,read()抛出一个ArrayIndexOutOfBoundsException .."
但是,当我运行此代码并输入超过10个字符时,不会ArrayIndexOutOfBoundsException抛出; 为什么会这样?
检查文档InputStream.read:
读取的字节数最多等于b的长度
因此read调用遵循数组的长度并将实际读取的字节数限制为该长度.当您输入超过10个字符时,这些附加字符将保留在输入流中.做另一个read,你会看到他们.
您可以导致IndexOutOfBoundsException使用InputStream.read(array, offset, length).