为什么不能重新打开封闭(标准)流? [英] Why is not possible to reopen a closed (standard) stream?

查看:101
本文介绍了为什么不能重新打开封闭(标准)流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.in 是提供用户输入数据的标准输入流。关闭后,无法重新打开此流。一个这样的例子是在使用扫描仪读取用户输入的情况下如下:

System.in is the "standard" input stream which supplies user input data. Once closed, this stream can not be re-opened. One such example is in the case of using a scanner to read the user input as follows:

public class Test {
    public static void main(String[] args) {

        boolean finished;

        do {
            Scanner inputScanner = new Scanner(System.in);
            finished = inputScanner.hasNext("exit");
            boolean validNumber = inputScanner.hasNextDouble();
            if (validNumber) {
                double number = inputScanner.nextDouble();

                System.out.print(number);
            } else if (!finished) {
                System.out.println("Please try again.");
            }
            inputScanner.close();
        } while (!finished);
    }
}

在此示例中,类型为<$ c的实例$ c> Scanner 已创建并用于从用户读取一系列数字(请忽略此代码的其他详细信息,超出此示例的范围,我知道应创建并关闭扫描程序在循环之外)。从用户输入中检索数字后,将关闭此扫描程序的实例(即输入流)。但是,当从用户请求另一个号码并创建新实例时,无法再次打开输入流。如果是这个例子,它会创建一个无限循环。

In this example, an instance of type Scanner is created and used to read a series of numbers from the user (please ignore other details with this code which go beyond the scope of this example, I know the scanner should be created and closed outside the loop). After a number is retrieved from user input, the instance of this Scanner (i.e., the input stream) is closed. However, when another number is requested from user, and new instance is created, the input stream cannot be opened again. In case of this example, it creates a infinite loop.

问题是:为什么不能重新打开一个封闭的流?

The question is: why is not possible to reopen a closed stream?

推荐答案


为什么不能用Java重新打开一个封闭的流?

why is not possible to reopen a closed stream in Java?

这就是Java流所代表的底层操作系统结构的本质。流本质上是一个数据管道。关闭它后,它就不再存在了。您可以在相同的端点之间创建一个新端点,但这会产生一个根本不同的流。我们可以考虑缓冲和流定位等实现注意事项,但这些都是副作用。

That's simply the nature of the underlying operating system constructs that Java streams represent. A stream is essentially a data conduit. Once you close it, it no longer exists. You may be able to create a new one between the same endpoints, but that yields a fundamentally different stream. We could go into implementation considerations such as buffering and stream positioning, but those are really side issues.

您还特别询问了标准流。这些是您无法重新创建的一些情况。操作系统为每个进程提供一组标准流。一旦它们关闭,就无法获得等价物。您可以在其位置放置不同的流,但无法将它们连接到原始端点。

You also asked specifically about the standard streams. These are some of the cases that you cannot recreate. The operating system provides each process with its set of standard streams. Once they are closed, there is no way to obtain equivalents. You can put different streams in their place, but you cannot connect them to the original endpoints.

这篇关于为什么不能重新打开封闭(标准)流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆