如何修复“IOException:流已关闭”问题使用 System.in 时出现异常?

发布于 2025-01-06 20:35:49 字数 600 浏览 6 评论 0原文

我正在编写一个简单的程序,使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2025-01-13 20:35:49

第一个消息将关闭它

br.close();

该流已关闭,因为您在读取文件名后发出的

。不要关闭该读取器,也不要为 System.in 创建新的读取器 - 只需重复使用该读取器即可。不过,请使用不同的文件来读取文件。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文