I have tried the following codes both have different approaches.
Approach 1: It breaks when executing in the latest version of Eclipse IDE say 2020-03 whereas it works fine in Mars IDE.
This problem is already asked on this How to display asterisk for input in Java?.
Approach 1:
Package test;
import java.io.*;
public class Test {
public static void main(final String[] args) {
String password = PasswordField.readPassword("Enter password:");
System.out.println("Password entered was:" + password);
}
}
class PasswordField {
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();
}
et.stopMasking();
return password;
}
}
class EraserThread implements Runnable {
private boolean stop;
public EraserThread(String prompt) {
System.out.print(prompt);
}
@SuppressWarnings("static-access")
public void run() {
while (!stop) {
System.out.print("\010*");
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}
Approach 2:
It does not work on Eclipse IDE but does work on the command line.
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}