“java.io.IOException: Stream closed” with new BufferedReader

无人久伴 提交于 2019-12-02 17:30:15

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/34552774/java-io-ioexception-stream-closed-with-new-bufferedreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!