从控制台窗口隐藏密码Java星号密码或阻止输入的字符串显示

时间:2014-11-20 21:55:29

标签: java input console passwords

public class Login {

    protected static String user, pass, host;
    Object conn;


    public void Login() throws SQLException
    {



    try {
      Class.forName ("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println ("Could not load the driver"); 
      }




    Scanner sc = new Scanner(System.in);
    Console console = System.console();

    System.out.println("Please Enter Username");
    user = sc.next();
    System.out.println("Please Enter Password");
    pass = sc.nextLine();
    System.out.println("Please Enter Host/IP Address");
    host = sc.next();
    System.out.println("Attempting Log In");



  Connection conn = (Connection) DriverManager.getConnection
                  ("jdbc:mysql://"+host+":3306/chessdb", user, pass);

只是一点帮助,一直在线查看阻止控制台窗口上显示的密码。是否有一种简单的方法可以输入文本根本不显示,或者只是星号来覆盖密码字段的输入?

3 个答案:

答案 0 :(得分:1)

使用readPassword()方法。

而不是像

那样使用扫描程序
System.out.println("Please Enter Password");
    pass = sc.nextLine();

使用:

    System.out.println("Please Enter Password");
    char[] passString = Console.readPassword();
    String pass = new String(passString );

答案 1 :(得分:0)

使用java.io.Console.readPassword()方法

请参阅以下链接中的API

https://docs.oracle.com/javase/7/docs/api/java/io/Console.html

答案 2 :(得分:0)

java.io.Console有一种方法可以在禁用输出的情况下读取密码:Console#readPassword