I would strongly recommend using a set up where Console
is used when possible, falling back to a Scanner
or Reader
when it is not.
However, there is a very ugly solution to the specific wording of this question, which I found here.
The solution is basically to repeatedly send the backspace (\b
) character to the console to hide whatever gets written. It's may be possible for you to formulate a more resource friendly version with some kind of listener, but I'm not sure about that.
Some example code that should do exactly this:
public class PwdConsole {
public static void main(String[] args) throws Exception {
ConsoleEraser consoleEraser = new ConsoleEraser();
System.out.print("Password? ");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
consoleEraser.start();
String pass = stdin.readLine();
consoleEraser.halt();
System.out.print("\b");
System.out.println("Password: '" + pass + "'");
}
class ConsoleEraser extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print("\b ");
}
public synchronized void halt() {
running = false;
}
}
}