如何修复“IOException:流已关闭”问题使用 System.in 时出现异常?
我正在编写一个简单的程序,使用 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();
但是当我调用第二个 br.readLine() 来读取另一个文件名时,出现以下异常:
线程“主”java.io.IOException中出现异常:流已关闭
我不明白如何关闭 System.in 流。 我犯了什么错误以及如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个消息将关闭它
该流已关闭,因为您在读取文件名后发出的
。不要关闭该读取器,也不要为
System.in
创建新的读取器 - 只需重复使用该读取器即可。不过,请使用不同的文件来读取文件。The stream is closed because you're closing it with the first
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.