0
package ReaderPack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReaderDemo {

    public static void main(String[] args) throws IOException {

        while (true) {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String msg = br.readLine();
            System.out.println(msg);
            br.close();
        }

    }

}

Output: Hello Hello Exception in thread "main" java.io.IOException: Stream closed at ReaderPack.ReaderDemo.main(ReaderDemo.java:13)

My Question: The first round of execution of while loop, I can input something via the keyboard. Why it does not allow me to do this a second time? I think every round of the while loop, a new BufferedReader br should be initiated with System.in, and the next round it should be a new BufferedReader stream, which is irrelevant with the previous one. Seems like if I close the previous stream, then even in the future round a new stream cannot be re-initiated? Thank you!

Mr.Snail
  • 51
  • 6
  • You close the stream **within** the while loop, so it can no longer work. Why not close it **after** the while loop, so that it remains open. Also, create the BufferedReader **before** the while loop so you can re-use it within the loop. – Hovercraft Full Of Eels Oct 13 '18 at 14:52
  • Always go through your code and ask yourself -- does this make sense? You must learn to do mental walk-throughs of your code, asking yourself the very same question as you do it -- also known as "[Rubber Duck Debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging)". – Hovercraft Full Of Eels Oct 13 '18 at 14:53
  • Also don't use a `while (true)` loop. There are well explained ways of using a while loop with a BufferedReader, and I urge you to search for them (easy to find, and I'll leave this exercise for you to do), and then use them. – Hovercraft Full Of Eels Oct 13 '18 at 14:54
  • 1
    So you're saying the System.in cannot be re-opened? – Mr.Snail Oct 13 '18 at 14:56
  • Yes, I'm saying *exactly* that. This is about Scanner [similar problem link](https://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in), but it applies to BufferedReader or anything that uses System.in – Hovercraft Full Of Eels Oct 13 '18 at 14:58
  • Thank you I understand it now. It's really helpful! – Mr.Snail Oct 13 '18 at 15:03
  • Once any stream has been closed it can't be reopened. If you want to keep using it, don't close it. – Peter Lawrey Oct 13 '18 at 15:06

0 Answers0