在命令行上隐藏输入

时间:2012-05-30 15:31:12

标签: java command-line input user-input command-prompt

我知道像Git和其他命令行界面能够隐藏用户的输入(对密码很有用)。有没有办法在Java中以编程方式执行此操作?我正在从用户那里获取密码输入,我希望他们的输入被“隐藏”在该特定行上(但不是全部)。这是我的代码(虽然我怀疑它会有所帮助......)

try (Scanner input = new Scanner(System.in)) {
  //I'm guessing it'd probably be some property you set on the scanner or System.in right here...
  System.out.print("Please input the password for " + name + ": ");
  password = input.nextLine();
}

5 个答案:

答案 0 :(得分:85)

试试java.io.Console.readPassword。你必须至少运行Java 6。

   /**
    * Reads a password or passphrase from the console with echoing disabled
    *
    * @throws IOError
    *         If an I/O error occurs.
    *
    * @return  A character array containing the password or passphrase read
    *          from the console, not including any line-termination characters,
    *          or <tt>null</tt> if an end of stream has been reached.
    */
    public char[] readPassword() {
        return readPassword("");
    }

请注意,这个doesn't work与Eclipse控制台一起使用。您必须从 true console / shell / terminal / prompt运行该程序才能测试它。

答案 1 :(得分:13)

是的,可以做到。这称为命令行输入掩蔽。您可以轻松实现此功能。

您可以使用单独的线程在输入时擦除回显的字符,并将其替换为星号。这是使用下面显示的EraserThread类完成的

import java.io.*;

class EraserThread implements Runnable {
   private boolean stop;

   /**
    *@param The prompt displayed to the user
    */
   public EraserThread(String prompt) {
       System.out.print(prompt);
   }

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

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

使用此线程

public class PasswordField {

   /**
    *@param prompt The prompt to display to the user
    *@return The password as entered by the user
    */
   public static String readPassword (String prompt) {
      EraserThread et = new EraserThread(prompt);
      Thread mask = new Thread(et);
      mask.start();

      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String password = "";

      try {
         password = in.readLine();
      } catch (IOException ioe) {
        ioe.printStackTrace();
      }
      // stop masking
      et.stopMasking();
      // return the password entered by the user
      return password;
   }
}

This Link详细讨论。

答案 2 :(得分:8)

JLine 2可能会引起关注。除了字符屏蔽外,它还提供命令行完成,编辑和历史记录功能。因此,它对基于CLI的Java工具非常有用。

屏蔽你的输入:

String password = new jline.ConsoleReader().readLine(new Character('*'));

答案 3 :(得分:3)

有:

Console cons;
char[] passwd;
if ((cons = System.console()) != null &&
    (passwd = cons.readPassword("[%s]", "Password:")) != null) {
    ...
    java.util.Arrays.fill(passwd, ' ');
}

source

但我不认为这适用于像Eclipse这样的IDE,因为程序是作为后台进程运行的,而不是带有控制台窗口的顶级进程。

另一种方法是使用伴随JPasswordField方法的actionPerformed摆动:

public void actionPerformed(ActionEvent e) {
    ...
    char [] p = pwdField.getPassword();
}

source

答案 4 :(得分:0)

班级Console有一个方法readPassword(),可以解决您的问题。