我正在阅读这本书Java™ I/O, 2nd Edition,而且还有这段代码:
try {
byte[] b = new byte[10];
System.in.read(b);
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}
从书中引用:
“..没有什么可以阻止你尝试将更多数据读入 阵列比不合适。如果你这样做,read()会抛出一个 ArrayIndexOutOfBoundsException异常..“
但是当我运行此代码并输入超过10个字符时,不会抛出ArrayIndexOutOfBoundsException
;那是怎么回事?
答案 0 :(得分:6)
查看InputStream.read
的文档:
读取的字节数最多等于b
的长度
因此read
调用遵循数组的长度,并将实际读取的字节数限制为该长度。输入超过例如10个字符,这些附加字符将保留在输入流中。做另一个read
,你会看到它们。
你可以使用InputStream.read(array, offset, length)
导致IndexOutOfBoundsException
。
答案 1 :(得分:0)
你的书错了,表达也很差。以下两个陈述是相互矛盾的:
“..没有什么可以阻止你尝试将更多数据读入 阵列比不合适。如果你这样做,read()会抛出一个 ArrayIndexOutOfBoundsException异常“。
我不知道为什么Elliotte Rusty Harold认为例外是“没有什么能阻止你”。它确实阻止了你,这就是它的目的。
事实是InputStream.read()
将读取至少1个且最多b.length
个字节,除非它检测到EOS而返回-1。
如果使用read(byte[] buffer, int offset, int length)
重载,如果“off [set]为负,len [gth]为负,或len [gth]大于b [uffer],则会抛出IndexOutOfBoundsException
。 length - off [set]“。