【发布时间】: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