The Scanner
documentation says that when one calls next()
on a closed stream then these two exceptions may be thrown:
NoSuchElementException - if no more tokens are available
IllegalStateException - if this scanner is closed
Furthermore hasNext()
may throw this exception:
IllegalStateException - if this scanner is closed
Now let's assume that we have this code:
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());
This will print word1
as expected. If we uncomment sc.close(); sc = new Scanner(fis);
a NoSuchElementException
will be thrown when sc.next()
will be executed.
This behaviour seems strange to me. Shouldn't hasNext()
and next()
throw an IllegalStateException
as the InputStream
is closed? Please, explain why this is happening.