在由关闭流初始化的 Scanner 上调用 next() 不会抛出 IllegalStateException
Calling next() on a Scanner initialized by a closed stream doesn't throw IllegalStateException
Scanner
documentation 表示当在一个关闭的流上调用 next()
时可能会抛出这两个异常:
NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed
此外 hasNext()
可能会抛出这个异常:
IllegalStateException - if this scanner is closed
现在假设我们有这段代码:
FileInputStream fis = new FileInputStream(new File("somefile"));
Scanner sc = new Scanner(fis);
// sc.close();
// sc = new Scanner(fis);
// somefile contents: word1 word2 word3
System.out.println(sc.next());
这将按预期打印 word1
。如果我们取消注释 sc.close(); sc = new Scanner(fis);
将在执行 sc.next()
时抛出 NoSuchElementException
。
我觉得这种行为很奇怪。 hasNext()
和 next()
不应该在 InputStream
关闭时抛出 IllegalStateException
吗?请解释为什么会这样。
您似乎误解了 Scanner
的文档。它说 next()
将抛出 NoSuchElementException
如果没有更多可用的令牌;当底层流结束或已关闭时就是这种情况。如果 扫描器本身 已关闭,它只会抛出 IllegalStateException
——这在你的问题中不会发生。
Scanner
documentation 表示当在一个关闭的流上调用 next()
时可能会抛出这两个异常:
NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed
此外 hasNext()
可能会抛出这个异常:
IllegalStateException - if this scanner is closed
现在假设我们有这段代码:
FileInputStream fis = new FileInputStream(new File("somefile"));
Scanner sc = new Scanner(fis);
// sc.close();
// sc = new Scanner(fis);
// somefile contents: word1 word2 word3
System.out.println(sc.next());
这将按预期打印 word1
。如果我们取消注释 sc.close(); sc = new Scanner(fis);
将在执行 sc.next()
时抛出 NoSuchElementException
。
我觉得这种行为很奇怪。 hasNext()
和 next()
不应该在 InputStream
关闭时抛出 IllegalStateException
吗?请解释为什么会这样。
您似乎误解了 Scanner
的文档。它说 next()
将抛出 NoSuchElementException
如果没有更多可用的令牌;当底层流结束或已关闭时就是这种情况。如果 扫描器本身 已关闭,它只会抛出 IllegalStateException
——这在你的问题中不会发生。