如何修复"IOException:流已关闭"使用System.in的异常? [英] How can I fix an "IOException: Stream closed" exception using System.in?

查看:94
本文介绍了如何修复"IOException:流已关闭"使用System.in的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的程序,该程序使用BufferedReader读取和处理文件内容.

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();

但是当我调用第二个br.readLine()来读取另一个文件名时,出现以下异常:

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

线程"main"中的异常java.io.IOException:流已关闭

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

我不明白如何关闭System.in流. 我犯了什么错误,我该如何解决?

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

推荐答案

由于您要使用第一个

br.close();

读取文件名后发出的

.

that you issue after having read the filename.

不要关闭该阅读器,也不要为System.in创建一个新的阅读器-只需重新使用该阅读器即可.不过,请使用其他文件读取文件.

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.

这篇关于如何修复"IOException:流已关闭"使用System.in的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆