0

我有一个使用 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;
}

在此先感谢您的帮助!

4

4 回答 4

4

只有一个控制台,而且只有一个System.in. 如果您关闭它,那么您将无法再读取它!你不需要关闭它BufferedReader,你也不应该。整个finally街区可以而且应该消失。

仔细阅读后,我什至不明白你为什么要首先创建BufferedReader- 它似乎没有任何功能。只需删除所有处理它的代码!

于 2012-06-08T21:14:11.227 回答
3

您在这里不需要任何阅读器,只需使用Console实例即可。

public String Func() {
        Console console = System.console();
        if (console == null)
            throw new IllegalStateException("No console available");

        try {
           String username = console.readLine("Username: ");
           String pwd = new String(console.readPassword("Password: "));
           return pwd;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
}

使用您的问题编辑进行编辑。只需使用 Console 类,它可以读取/写入,您不需要任何读取器/写入器。

于 2012-06-08T21:17:22.737 回答
1

你不应该关闭你的Console. 保持打开状态,直到您的程序不再需要从中读取。

于 2012-06-08T21:16:56.347 回答
1

改用 java.util.Scanner 之类的东西,正如其他人所说,不要担心尝试关闭 system.in。

干净多了:

Scanner in = new Scanner(System.in);
String password  = in.nextLine(); 
String username  = in.nextLine();

无需整理/异常处理。

于 2012-06-08T21:21:02.023 回答