Hello World!, I have a question regarding the close() method of the Input Stream class. Here is my code ->
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
}
}
Line by line I have written what I feel should happen. But the program when ran raised exception as follows ->
java.io.IOException: Stream closed
When I initially enter abcdefghij through the console, do all of these characters go into the consoleInputStream object. What I feel is it should. This is because the skip() method works fine i.e. it skips the next two bytes. Hence the consoleInputStream object must have all the characters inside.
But if this happens why do I get exception when I try to read something from the consoleInputStream object after closing it. If the stream already has these characters inside it, it shouldn't matter if the connection with the console is closed or not.
I have just started working with the streams and I want to be conceptually strong in it. Can anybody explain what exactly happens under the hood and where am I conceptually wrong??