What does scanner.close() do?

前端 未结 1 1204
温柔的废话
温柔的废话 2020-12-09 18:29

Say I have the following example code:

Scanner scan1 = new Scanner(System.in);    // declaring new Scanner called scan1
int x = scan1.nextInt();    // scan f         


        
相关标签:
1条回答
  • 2020-12-09 18:57

    Yes, it does mean that 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 terminates 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)
    

    Once closed, you won't be able to use System.in for the rest of your program. The fact that close() is passed through is nice because it means you don't have to maintain a separate reference to the input stream so that you can close it later, for example:

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

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

    In most cases you won't want to close System.in, so you won't want to call .close() in that case.

    0 讨论(0)
提交回复
热议问题