Java密码如何输出显示*号?

IntelliJ IDEA软件 java银行系统怎么将密码输出改成*号?

我想要达到的结果

img

img

两种方案,你看看你需要的是什么吧~

1. 使用 System.console()

public class Test {
    public static void main(String[] args) throws IOException {
        Console console = System.console();
        System.out.println("请输入密码: ");
        char[] pas = console.readPassword();
        System.out.println(new String(pas));
    }
}

效果大概是:空白的输入,不可见。但是此方法不可以在IDE内的控制台使用,会报空指针,只能在真实的控制台使用

img

2. 开辟单线程覆盖输入


import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

public class Test {
    public static void main(String[] args) throws IOException {
        String password = readPassword("请输入密码: ");
        System.out.println(password);
    }

    public static String readPassword(String prompt) {
        EraserThread et = new EraserThread(prompt);
        Thread mask = new Thread(et);
        mask.start();

        StringBuilder password = new StringBuilder();
        InputStream inputStream = System.in;
        byte[] buffer = new byte[1];
        List<Byte> result = new LinkedList<>();

        try {
            while (inputStream.read(buffer) != -1) {
                if (buffer[0] == 10) {
                    // stop masking
                    et.stopMasking();
                    break;
                }
                result.add(buffer[0]);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        for (Byte b : result) {
            password.append((char) b.byteValue());
        }
        // return the password entered by the user
        return password.toString();
    }

    static class EraserThread implements Runnable {
        private volatile boolean stop;

        public EraserThread(String prompt) {
            System.out.print(prompt + " ");
        }

        public void run() {
            stop = true;
            while (stop) {
                System.out.print("\010*");
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            }
        }

        /**
         * Instruct the thread to stop masking
         */
        public void stopMasking() {
            this.stop = false;
        }
    }
}

效果大概是

img

可以实现你说的*号效果,也可以在IDE内部的控制台实现覆盖效果,但是无法正常接收输入,在真实的控制台可以正确接收输入

可以使用 Console.readPassword 方法读取密码

Console console = System.console();

控制台好像不能玩这么花的