小编典典

Java System.console()返回null

java

我曾经使用readLineof BufferedReader来获取用户的输入/新密码,但想屏蔽该密码,所以我尝试使用java.io.Consoleclass。问题是在Eclipse中调试应用程序时System.console()返回null。我是Java和``Eclipse的新手,不确定这是否是最好的方法吗?我右键单击源文件,然后选择“调试为”>“ Java应用程序”。有什么解决方法吗?


阅读 929

收藏
2020-02-28

共1个答案

小编典典

此代码段应该可以解决问题:

private String readLine(String format, Object... args) throws IOException {
    if (System.console() != null) {
        return System.console().readLine(format, args);
    }
    System.out.print(String.format(format, args));
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
    return reader.readLine();
}

private char[] readPassword(String format, Object... args)
        throws IOException {
    if (System.console() != null)
        return System.console().readPassword(format, args);
    return this.readLine(format, args).toCharArray();
}

在Eclipse中进行测试时,你的密码输入将清晰显示。至少,你将能够进行测试。只是在测试时不要输入你的真实密码。保留供生产使用

2020-02-28