是可以做到的。這稱爲命令行輸入掩碼。您可以輕鬆實現。
您可以使用單獨的線程擦除正在輸入的回顯字符,並用星號替換它們。這是使用下面
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;
}
}
所示的EraserThread類使用此線程
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;
}
}
This Link詳細討論完成。
+1讓我知道它在Eclipse控制檯中不起作用(儘管我使用Netbeans,但顯然它不起作用)。 – kentcdodds
示例練習:http://www.tutorialspoint.com/java/io/console_readpassword.htm – mavis
由於他們使用javaw,在大多數IDE中不起作用。請參閱http://stackoverflow.com/a/26473083/3696510 – muttonUp