scanner.close()有什么作用?

Koo*_*ing 11 java java.util.scanner

说我有以下示例代码:

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
Run Code Online (Sandbox Code Playgroud)

Scanner课堂上阅读了Oracle文档,并发现了这个:

当扫描仪关闭时,如果源实现了Closeable接口,它将关闭其输入源.

这是否意味着一旦a Scanner(of System.in)关闭,我将不再能够System.in在整个Java程序中使用?或者这是否意味着我将不再能够在整个班级使用它?还是只有方法?或者只是它的范围?

我的另一个问题是,Scanner是否仅限于声明的范围(类似于原始数据类型)?

Fat*_*ror 6

是的,这确实意味着System.in将被关闭.测试用例:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码终止于

$ 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)
Run Code Online (Sandbox Code Playgroud)

关闭后,您将无法使用System.in其余程序.close()传递的事实很好,因为这意味着您不必维护对输入流的单独引用,以便以后可以关闭它,例如:

scanner = new Scanner(foo.somethingThatMakesAnInputStream());
Run Code Online (Sandbox Code Playgroud)

您可以这样做并调用.close()扫描程序来关闭底层流.

在大多数情况下,您不想关闭System.in,因此您不希望.close()在这种情况下打电话.

  • +1只是试用一个测试用例,从而避开了猜测和理论的陷阱. (2认同)