本文介绍了Scanner.close()有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下示例代码:

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

我阅读了Scanner上的 Oracle文档.课,并遇到了这个问题:

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

这是否意味着一旦关闭了Scanner(位于System.in中),我将无法在整个Java程序中使用System.in?还是这意味着我将无法在整个课程中使用它?还是只有方法?还是只有它的范围?

Does this mean that once a Scanner (of System.in) is closed, I will no longer be able to use System.in throughout the entire Java program? Or does it mean I will no longer be able to use it throughout the class? Or only the method? Or only its scope?

我的另一个问题是,扫描仪是否受其声明的范围限制(类似于原始数据类型)?

Another question I have is, is a Scanner restricted to the scope it was declared in (similar to the primitive data types)?

推荐答案

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

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();
    }
}

此代码以

$ 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()的事实很好,因为它意味着您不必维护对输入流的单独引用,以便以后可以关闭它,例如:

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());

您可以执行此操作,然后在扫描仪上调用.close()以关闭基础流.

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

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

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

这篇关于Scanner.close()有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:54