Gau*_*uls 77 java eclipse console springsource
我用readLine的BufferedReader获得输入/从用户的新密码,但希望屏蔽密码,所以我试图用java.io.Console类.问题是在Eclipse中调试应用程序时System.console()返回null.我是Java和Eclipse的新手,不确定这是最好的实现方式吗?我右键单击源文件并选择"Debug As">"Java Application".有没有解决方法?
for*_*ian 33
这段代码应该可以解决问题:
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中进行测试时,您的密码输入将以明文形式显示.至少,你将能够测试.只是在测试时不要输入真实密码.保留它用于生产用途;).
小智 8
在尝试编写简单的命令行应用程序时,我也遇到了这个问题.
从System.in创建自己的BufferedReader对象的另一种方法是使用java.util.Scanner,如下所示:
import java.util.Scanner;
Scanner in;
in = new Scanner(System.in);
String s = in.nextLine();
当然,这不是Console的替代品,但可以让您访问各种不同的输入功能.
以下是有关Oracle Scanner的更多文档.
根据API:
"如果虚拟机是从交互式命令行启动的,而不重定向标准输入和输出流,那么它的控制台将存在,并且通常会连接到启动虚拟机的键盘和显示器.如果虚拟机已启动例如,通过后台作业调度程序,它通常不会有控制台."
从 Netbeans 运行应用程序时收到此错误消息。从其他答案来看,从 IDE 运行应用程序时似乎会发生这种情况。如果你看一下这个问题:Trying to read from the console in Java,那是因为
大多数 IDE 使用 javaw.exe 而不是 java.exe 来运行 Java 代码
解决方案是使用command line/terminal来获取Console.