ken*_*dds 58 java command-line user-input input command-prompt
我知道像Git和其他命令行界面能够隐藏用户的输入(对密码很有用).有没有办法在Java中以编程方式执行此操作?我正在从用户那里获取密码输入,我希望他们的输入被"隐藏"在该特定行上(但不是所有这些).这是我的代码(虽然我怀疑它会有所帮助......)
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();
}
Run Code Online (Sandbox Code Playgroud)
ada*_*shr 86
试试java.io.Console.readPassword.你必须至少运行Java 6.
/**
* 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("");
}
Run Code Online (Sandbox Code Playgroud)
请注意,这不适用于Eclipse控制台.您必须从真正的控制台/ shell /终端/提示符运行该程序才能测试它.
Vij*_*bey 12
是的,可以做到.这称为命令行输入掩蔽.您可以轻松实现此功能.
您可以使用单独的线程在输入时擦除回显的字符,并用星号替换它们.这是使用下面显示的EraserThread类完成的
import java.io.*;
class EraserThread implements Runnable {
private boolean stop;
/**
*@param The prompt displayed to the user
*/
public EraserThread(String prompt) {
System.out.print(prompt);
}
/**
* Begin masking...display asterisks (*)
*/
public void run () {
stop = true;
while (stop) {
System.out.print("\010*");
try {
Thread.currentThread().sleep(1);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
}
}
/**
* Instruct the thread to stop masking
*/
public void stopMasking() {
this.stop = false;
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个线程
public class PasswordField {
/**
*@param prompt The prompt to display to the user
*@return The password as entered by the user
*/
public static String readPassword (String prompt) {
EraserThread et = new EraserThread(prompt);
Thread mask = new Thread(et);
mask.start();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String password = "";
try {
password = in.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
// stop masking
et.stopMasking();
// return the password entered by the user
return password;
}
}
Run Code Online (Sandbox Code Playgroud)
本链接详细讨论.
JLine 2可能会引起关注.除了字符屏蔽外,它还提供命令行完成,编辑和历史记录功能.因此,它对基于CLI的Java工具非常有用.
掩盖你的输入:
String password = new jline.ConsoleReader().readLine(new Character('*'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77905 次 |
| 最近记录: |