Hello World!, 我有一个关于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
}
}
逐行我写了我认为应该发生的事情。但是程序在运行时引发异常如下 - &gt;
java.io.IOException: Stream closed
当我最初通过控制台输入 abcdefghij 时,所有这些字符都会进入consoleInputStream对象。我觉得应该是什么。这是因为skip()方法工作正常,即它跳过接下来的两个字节。因此,consoleInputStream对象必须包含所有字符。
但如果发生这种情况,为什么在关闭后尝试从consoleInputStream对象中读取内容时会出现异常。如果流中已经包含这些字符,那么与控制台的连接是否关闭并不重要。
我刚开始使用溪流,我想在概念上很强大。谁能解释一下究竟发生了什么?我在概念上哪里错了?
答案 0 :(得分:0)
您需要先阅读javadoc。 InputStream
表示在大多数情况下与基础系统相关的内容的连接,在关闭流后,释放与此流关联的任何系统rosource,并且在调用该方法后此对象仍然无效。