I am trying to read input from console using two classes in the same method InputStreamReader and BufferedReader . I have closed the stream of former class and read input again but now using latter class. It is showing error if I close the former class stream before invoking the BufferedReader stream read() method. But when closing the InputStreamReader stream at the end of the method, it is working fine.
My thoughts are - Since I have closed the stream of the former used class, latter stream is independent of it and thus should not affect the running of code.
public static void main(String[] args) throws Exception {
//File file = new File("D:\\IOSUMIT\\new_file.txt");
InputStreamReader isr= new InputStreamReader(System.in);
System.out.println("your input " + (char)isr.read());
isr.close(); //here error occurs
InputStreamReader isrp= new InputStreamReader(System.in); // Line 1
BufferedReader br = new BufferedReader(isrp);
int temp = br.read();
System.out.println("your input Buffered" + (char)temp);
br.close();
OUTPUT ERROR
4
your input 4Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.read(Unknown Source)
at IO.Q7.main(Q7.java:60)
Lets start with this:
isr.close(); //here error occurs
Actually, that is not where the error occurs. That is a red herring. According to the stacktrace, the exception is actually thrown by the following statement:
int temp = br.read();
Which makes sense. The isr.close()
is closing both the Reader and the input stream that it wraps. That input stream is the System.in
stream.
So, when you then create a second InputStreamReader
and BufferedReader
you are wrapping a stream that you have previously closed.
Hence, when you try to read from your new readers, you get an exception.
Solution: Once closed, the System.in
stream will stay closed. So DON'T close System.in
.
You asked:
Would not input stream be open again at commented Line 1 inside the BufferReader constructor ?
InputStreamReader isrp= new InputStreamReader(System.in); // Line 1
Short answer: No.
The new
is creating a new InputStreamReader
instance that wraps the current value of System.in
. In this case, that value is a reference for a FileInputStream
object for file descriptor 0 ... which you previously closed.