What does scanner.close () do?

Let's say I have the following code example:

Scanner scan1 = new Scanner(System.in); // declaring new Scanner called scan1 int x = scan1.nextInt(); // scan for user input and set it to x System.out.println(x); // print the value of x scan1.close(); // closes the scanner (I don't know exactly what this does) Scanner scan2 = new Scanner(System.in); // declaring new Scanner called scan1 int y = scan2.nextInt(); // scan for user input and set it to y System.out.println(y); // print the value of y 

I read the Oracle documentation in the Scanner class and came across this:

When the scanner is closed, it will close its input source if the source implements the Closeable interface.

Does this mean that after closing Scanner (from System.in ) I will no longer use System.in in the entire Java program? Or does it mean that I can no longer use it in the whole class? Or just a method? Or just its volume?

Another question I have is Scanner, limited to the area in which it was declared (similar to primitive data types)?

+8
java java.util.scanner
source share
1 answer

Yes, that means System.in will be closed. Test case:

 import java.util.*; public class CloseScanner { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); scanner.close(); System.in.read(); } } 

This code exits with

 $ java CloseScanner Exception in thread "main" java.io.IOException: Stream closed at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:162) at java.io.BufferedInputStream.fill(BufferedInputStream.java:206) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at CloseScanner.main(CloseScanner.java:7) 

After closing, you will not be able to use System.in for the rest of your program. The fact that close() is passed in is nice, because it means you don't need to maintain a separate link to the input stream so that you can close it later, for example:

 scanner = new Scanner(foo.somethingThatMakesAnInputStream()); 

You can do this and call .close() on the scanner to close the underlying stream.

In most cases, you do not need to close System.in , so you do not want to call .close() in this case.

+5
source share

All Articles