当读取长度大于目标长度时,System.in.read方法不会抛出ArrayIndexOutOfBoundsException

Ziv*_*Ziv 0 java exception

我正在阅读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抛出; 为什么会这样?

pb2*_*b2q 6

检查文档InputStream.read:

读取的字节数最多等于b的长度

因此read调用遵循数组的长度并将实际读取的字节数限制为该长度.当您输入超过10个字符时,这些附加字符将保留在输入流中.做另一个read,你会看到他们.

可以导致IndexOutOfBoundsException使用InputStream.read(array, offset, length).