当System.console()返回null时,如何处理java passwd读取? [英] How to handle java passwd reading when System.console() returns null?

查看:193
本文介绍了当System.console()返回null时,如何处理java passwd读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个提示输入passwd的命令行程序,我不希望它对密码字符进行本地回显。经过一些搜索后,我偶然发现了 System.console()。readPassword(),这似乎很好,除了在Unix中处理管道时。因此,当我调用它时,我的示例程序(如下)工作正常:

I'm writing a commandline program that prompts for a passwd and I don't want it to do local echo of the password characters. After some searches, I have stumbled upon System.console().readPassword(), which seems great, except when dealing with pipes in Unix. So, my example program (below) works fine when I invoke it as:

% java PasswdPrompt

但当我调用它时,Console == null失败

but fails with Console == null when I invoke it as

% java PasswdPrompt | less

% java PasswdPrompt < inputfile

恕我直言,这似乎是一个JVM问题,但我不能成为唯一拥有JVM问题的人遇到这个问题所以我不得不想象有一些简单的解决方案。

IMHO, this seems like a JVM issue, but I can't be the only one who has run into this problem so I have to imagine there are some easy solutions.

任何一个?

谢谢提前

import java.io.Console;

public class PasswdPrompt {
    public static void main(String args[]) {
        Console cons = System.console();
        if (cons == null) {
            System.err.println("Got null from System.console()!; exiting...");
            System.exit(1);
        }
        char passwd[] = cons.readPassword("Password: ");
        if (passwd == null) {
            System.err.println("Got null from Console.readPassword()!; exiting...");
            System.exit(1);
        }
        System.err.println("Successfully got passwd.");
    }
}


推荐答案

所以由于某种原因,当System.console()返回null时,终端回显总是关闭,所以我的问题变得微不足道。以下代码完全按照我的意愿工作。感谢您的帮助。

So, for some reason, when System.console() returns null, terminal echo is always off, so my problem becomes trivial. The following code works exactly as I wanted. Thanks for all the help.

import java.io.*;


public class PasswdPrompt {
    public static void main(String args[]) throws IOException{
        Console cons = System.console();
        char passwd[];
        if (cons == null) {
            // default to stderr; does NOT echo characters... not sure why
            System.err.print("Password: ");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                                            System.in));
            passwd= reader.readLine().toCharArray();
        }
        else {
            passwd = cons.readPassword("Password: ");
        }
        System.err.println("Successfully got passwd.: " + String.valueOf(passwd));
    }

}

这篇关于当System.console()返回null时,如何处理java passwd读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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