我有一个使用 readPassword() 从控制台读取的函数。在一个程序迭代中多次调用此函数。但是,一旦到达 readPassword() 行,我就会不断收到 java io 异常。我注意到当我从 finally 子句中删除 close() 语句时,此错误消失了。为什么会发生这种情况,我应该何时正确关闭阅读器?
public void Func()
{
Console console = System.console();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
if (console == null)
System.out.println("Error!");
try
{
char[] pwd = console.readPassword();
String password = new String(pwd);
System.out.println("PW: " + password);
String input = reader.readLine();
System.out.println("UserNm: " + input);
} catch (IOException e) {
System.out.println("IO EXCEPTION");
} finally {
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
System.out.println("error");
}
}
}
return null;
}
在此先感谢您的帮助!