How can I fix an “IOException: Stream closed” exception using System.in?

梦想的初衷 提交于 2019-11-26 18:35:40

问题


I'm writing a simple program that reads and processes file content using a BufferedReader.

BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );

System.out.println("Enter the file name to read");
String fileName = br.readLine();
br.close();

// Process file contents

br = new BufferedReader( new InputStreamReader(System.in) );
System.out.println("Enter another file name to read");
fileName = br.readLine();
br.close();

But when I call second br.readLine() to read another file name, I get the following exception:

Exception in thread "main" java.io.IOException: Stream closed

I don't understand how the System.in stream can be closed. What mistake am I making and how do I fix this?


回答1:


The stream is closed because you're closing it with the first

br.close();

that you issue after having read the filename.

Don't close that reader, and don't create a new one for System.in - just re-use that one. Use a different one for reading from the file though.



来源:https://stackoverflow.com/questions/9349580/how-can-i-fix-an-ioexception-stream-closed-exception-using-system-in

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