我正在编写一个命令行程序,它提示输入passwd,我不希望它对密码字符进行本地回显。经过一些搜索,我偶然发现了System.console().readPassword(),这似乎很棒,除了在Unix中处理管道时。因此,我的示例程序(如下所示)在调用它时运行良好,如下所示:
% java PasswdPrompt但是当我调用控制台== null时,它会失败
% java PasswdPrompt | less或
% java PasswdPrompt < inputfileIMHO,这似乎是一个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.");
}
}发布于 2011-03-16 14:16:59
来自Java 文档页面:
如果System.console返回NULL,那么控制台操作是不允许的,这要么是因为操作系统不支持它们,要么是因为程序是在非交互式环境中启动的。
这个问题很可能是因为使用管道脱离了“交互式”模式,并且使用输入文件作为System.in使用,因此没有Console。
** 更新 **
这是一个快速的解决办法。在main方法的末尾添加以下行:
if (args.length > 0) {
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(args[0]));
out.print(passwd);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) out.close();
}
}并调用您的应用程序,如
$ java PasswdPrompt .out.tmp; less .out.tmp; rm .out.tmp但是,提示密码将驻留在明文(尽管是隐藏的)文件中,直到命令终止为止。
发布于 2011-03-18 04:03:37
因此,由于某种原因,当System.console()返回null时,终端回显总是关闭的,所以我的问题变得微不足道。下面的代码完全符合我的要求。谢谢你的帮助。
import java.io.*;
public class PasswdPrompt {
public static void main(String args[]) throws IOException{
Console cons = System.console();
char passwd[];
if (cons == null) {
// default to stderr; does NOT echo characters... not sure why
System.err.print("Password: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
passwd= reader.readLine().toCharArray();
}
else {
passwd = cons.readPassword("Password: ");
}
System.err.println("Successfully got passwd.: " + String.valueOf(passwd));
}
}https://stackoverflow.com/questions/5326406
复制相似问题