假设我有以下示例代码:
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
我读了Oracle documentation on the Scanner
class并发现了这个:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
这是否意味着一旦 Scanner
(System.in
)关闭,我将无法再使用 System.in
> 贯穿整个Java程序?或者这是否意味着我将无法在整个类里面使用它?还是只有方法?或者只是它的范围?
我的另一个问题是,扫描仪是否仅限于其声明的范围(类似于原始数据类型)?
最佳答案
是的,这确实意味着 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();
}
}
此代码终止于
$ 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)
关闭后,您将无法在程序的其余部分使用 System.in
。传递 close()
的事实很好,因为这意味着您不必维护对输入流的单独引用,以便稍后可以关闭它,例如:
scanner = new Scanner(foo.somethingThatMakesAnInputStream());
您可以执行此操作并在扫描器上调用 .close()
来关闭底层流。
在大多数情况下,您不想关闭 System.in
,因此在这种情况下您也不想调用 .close()
。
关于java - Scanner.close() 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245468/