我正在编写一个命令行程序,需要提示用户输入密码,但不想在屏幕上显示出密码字符。经过一些搜索,我发现System.console().readPassword()
这个方法很适合我的需求,但是在Unix管道处理时会出现问题。因此,当我像下面这样调用示例程序时:
% java PasswdPrompt
当我这样调用时,控制台为null,导致失败:
% java PasswdPrompt | less
或者
% java PasswdPrompt < inputfile
依我看,这似乎是一个JVM问题,但我不可能是唯一遇到这个问题的人,所以我想肯定有些解决方案。
有人知道吗?
提前感谢。
import java.io.Console;
public class PasswdPrompt {
public static void main(String args[]) {
Console cons = System.console();
if (cons == null) {
System.err.println("Got null from System.console()!; exiting...");
System.exit(1);
}
char passwd[] = cons.readPassword("Password: ");
if (passwd == null) {
System.err.println("Got null from Console.readPassword()!; exiting...");
System.exit(1);
}
System.err.println("Successfully got passwd.");
}
}