隐藏命令行输入 [英] Hide input on command line
问题描述
我知道像 Git 等命令行界面能够隐藏用户的输入(对密码很有用).有没有办法在 Java 中以编程方式执行此操作?我正在从用户那里输入密码,我希望他们的输入在该特定行上隐藏"(但不是全部).这是我的代码(虽然我怀疑它会有所帮助......)
I know that command line interfaces like Git and others are able to hide input from a user (useful for passwords). Is there a way to programmtically do this in Java? I'm taking password input from a user and I would like their input to be "hidden" on that particular line (but not on all of them). Here's my code for it (though I doubt it would be helpful...)
try (Scanner input = new Scanner(System.in)) {
//I'm guessing it'd probably be some property you set on the scanner or System.in right here...
System.out.print("Please input the password for " + name + ": ");
password = input.nextLine();
}
推荐答案
尝试 java.io.Console.readPassword
.不过,您必须至少运行 Java 6.
Try java.io.Console.readPassword
. You'll have to be running at least Java 6 though.
/**
* Reads a password or passphrase from the console with echoing disabled
*
* @throws IOError
* If an I/O error occurs.
*
* @return A character array containing the password or passphrase read
* from the console, not including any line-termination characters,
* or <tt>null</tt> if an end of stream has been reached.
*/
public char[] readPassword() {
return readPassword("");
}
但请注意,这 不适用于 Eclipse 控制台.您必须从 true 控制台/shell/终端/提示中运行该程序才能对其进行测试.
Beware though, this doesn't work with the Eclipse console. You'll have to run the program from a true console/shell/terminal/prompt to be able to test it.
这篇关于隐藏命令行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!