Java System.console()返回null

发布于 2021-02-02 23:04:27

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

关注者
0
被浏览
73
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看