隐藏命令行上的输入 [英] Hide input on command line

查看:124
本文介绍了隐藏命令行上的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道像Git和其他人的命令行界面能够隐藏来自用户的输入(对密码有用)。有没有办法在Java中以编程方式做到这一点?我从用户的密码输入,我想他们的输入隐藏在该特定行(但不是所有的)。这里是我的代码(虽然我怀疑它会有所帮助...)

I know that command line interfaces like Git and others are able to hide input from a user (useful for passwords). Is there a way to programmtically do this in Java? I'm taking password input from a user and I would like their input to be "hidden" on that particular line (but not on all of them). Here's my code for it (though I doubt it would be helpful...)

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


推荐答案

http://docs.oracle.com/javase/7/docs/api/java/io/Console.html#readPassword%28%29\">java.io.Console.readPassword

Try java.io.Console.readPassword. You'll have to be running at least Java 6 though.

   /**
    * 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 /终端/提示运行该程序才能测试该程序。

Beware though, this doesn't work with the Eclipse console. You'll have to run the program from a true console/shell/terminal/prompt to be able to test it.

这篇关于隐藏命令行上的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆