隐藏命令行输入

新手上路,请多包涵

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

原文由 kentcdodds 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 672
2 个回答

尝试 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/终端/提示符运行该程序才能对其进行测试。

原文由 adarshr 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

此链接 详细讨论。

原文由 Vijay Shanker Dubey 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题