1

Many people asked question like that but this one is a little bit different. Here is the code:

public static BufferedReader reader;    
public static String readString() throws IOException {
            reader = new BufferedReader(new InputStreamReader(System.in));
            String s = reader.readLine();
            reader.close();
            return s;
        }

While program runtime readString method is invoked many times. The second call causes exception: stream closed. I can not understand: why it ends up so? Every time we declare new BufferedReader. So the stream must be also new. Or not?

If not, how should I organize my program so that it will close reader after all invocations and after my program is over?

2 Answers 2

3

Because System.in is same Object (public final static InputStream in; of System class) both method calls are using, closing in one method will automatically close System.in for other method. You should close the BufferedReader from outside(as I can see it's public) the method once you finish calling readString and so it will ultimately close underlying System.in.

Sign up to request clarification or add additional context in comments.

Comments

2

Closing the BufferedReader closes System.in. You shouldn't close it at all, and you shouldn't keep creating a new one either: you will lose data. Use the same one for the life of the process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.