Java多线程 例子 cmd窗口下 实现输入密码星号显示

2018-03-18  本文已影响24人  zheting
import java.util.Scanner;

/**
 * Create Time: 2018-03-17 07:28
 *
 * @author sheting
 */
public class TestEraserThread {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("请输入名称:");
            String name = scanner.next();

            System.out.print("请输入密码:");
            EraserThread eraserThread = new EraserThread('#');
            eraserThread.start();
            String password = scanner.next();
            eraserThread.setActive(false);

            if ("sheting".equals(name) && "123456".equals(password)) {
                System.out.println(String.format("欢迎%s", name));
                break;
            } else {
                System.out.println("用户名或密码输入错误!请重新输入");
            }
        }
    }
}


class EraserThread extends Thread {
    private boolean active;
    private String mask;

    public EraserThread() {
        this('*');
    }

    public EraserThread(char maskChar) {
        active = true;
        mask = "\010" + maskChar;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public boolean isActive() {
        return active;
    }

    @Override
    public void run() {
        while (isActive()) {
            System.out.print(mask);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:


说明:在文本模式输出\010表示返回一个字符位置。

在Java1.6之后可以使用console.readPassword()方法隐藏用户输入的文本。

import java.io.Console;

/**
 * Create Time: 2018-03-17 09:19
 *
 * @author sheting
 */
public class Test {
    public static void main(String[] args) {
        Console console = System.console();

        if (console == null) {
            System.out.println("Couldn't get Console instance, maybe you're running this from within an IDE?");
            System.exit(0);
        }

        char passwordArray[] = console.readPassword("Enter your secret password: ");
        console.printf("Password entered was: %s%n", new String(passwordArray));
    }
}

运行结果:

上一篇 下一篇

猜你喜欢

热点阅读