Java replace password with asterisk on console

https:‮ual.www//‬tturi.com
Java replace password with asterisk on console

How to hide password while getting input from console in java

We can create another thread to erase password characters:

the character 010 is backspace.

/**
 * @author lautturi.com 
 * Java example:  Hide the entered password on Java console
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class ThreadErase implements Runnable {
    private boolean complete;
    public ThreadErase(String prompt) {
        System.out.print(prompt);
    }
    public void run() {
    	complete = true;
        while (complete) {
            System.out.print("\010*");
            try {
                Thread.currentThread().sleep(1);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }

    public void enterComplete() {
        this.complete = false;

    }
}
public class Lautturi {
	public static void main(String[] args)  {
		ThreadErase td = new ThreadErase("Enter your password: ");
        Thread t = new Thread(td);
        t.start();
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            String password = br.readLine();
            td.enterComplete();
            System.out.println("\nYour password is: " + password);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
	}
}
Created Time:2017-10-04 15:04:23  Author:lautturi