【问题标题】:close() method of the InputStream classInputStream 类的 close() 方法
【发布时间】:2017-12-05 22:02:12
【问题描述】:

你好,世界! 我对 Input Stream 类的 close() 方法有疑问。这是我的代码->

public class Main{
    InputStream consoleInputStream = System.in;
    byte[] bytes = new byte[2];

    consoleInputStream.read(bytes); // I gave the input --> abcdefghij and then enter key(line feed). 
                                    // Hence, abcdefghij and line feed(ASCII - 10) have all entered into consoleInputStream object. 
                                    // The first two bytes i.e. a and b have entered into bytes array.

    for(int i = 0; i < bytes.length; i++){
        System.out.print((char)bytes[i]); // it should print ab
    }

    consoleInputStream.skip(2); // should skip the next two bytes i.e. cd

    consoleInputStream.close(); // closes the connection with console.
                                // I am drawing analogy with the fileInputStream close()

    consoleInputStream.read(bytes); // should read the next two bytes from the consoleInputStream object i.e. e and f, and store them in bytes array.
                                    // Although the stream is closed i.e. connection with the console is closed but the stream already has these characters.

     for(int i = 0; i < bytes.length; i++){
        System.out.print((char)bytes[i]); // should print ef
    }
}

我逐行写下了我认为应该发生的事情。但是程序运行时引发异常如下 ->

java.io.IOException: Stream closed

当我最初通过控制台输入 abcdefghij 时,是否所有这些字符都进入了 consoleInputStream 对象。我的感觉是应该的。这是因为 skip() 方法工作正常,即它跳过了接下来的两个字节。因此,consoleInputStream 对象必须包含所有字符。

但是如果发生这种情况,为什么我在关闭 consoleInputStream 对象后尝试从它读取某些内容时会出现异常。如果流中已经包含这些字符,则与控制台的连接是否关闭都无关紧要。

我刚刚开始使用流,我希望在概念上更强大。谁能解释一下幕后到底发生了什么,我在概念上哪里错了?

【问题讨论】:

  • 在流上调用close 应该是你做的最后一件事。在流关闭后尝试对其执行任何操作将导致此异常。
  • 另外,你应该永远关闭System.in
  • 既然已经有了变量System.in;,为什么还要分配InputStream consoleInputStream = System.in;
  • 谢谢乔。我明白你的意思:) 但是请你告诉我 close() 方法实际上做了什么,释放了与流相关的任何系统资源。如果是这样,即使我调用了它的 close 方法,流仍然存在,所以它里面的字符也是如此。那为什么会引发异常呢?
  • InputStream.read() 的文档说,如果流已关闭,它将引发异常。这种行为应该不足为奇。

标签: java stream ioexception


【解决方案1】:

您需要先阅读 javadoc。 InputStream 在大多数情况下表示与底层系统相关的东西的连接,在关闭流之后,与该流关联的任何系统资源都被释放,并且在您调用该方法后该对象仍然无效。

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 2014-03-23
    • 2016-03-19
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多