隐藏命令行上的输入

我知道像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();
}

答案 1

尝试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("");
    }

但要小心,这不适用于Eclipse控制台。您必须从真正的控制台/shell/终端/提示符运行程序才能对其进行测试。


答案 2

是的,可以做到。这称为命令行输入屏蔽。您可以轻松实现这一点。

您可以使用单独的线程在输入回显字符时擦除这些字符,并用星号替换它们。这是使用如下所示的 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;
   }
}

此链接将详细讨论。


推荐