首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当System.console()返回null时,如何处理java passwd读取?

当System.console()返回null时,如何处理java passwd读取?
EN

Stack Overflow用户
提问于 2011-03-16 14:01:50
回答 2查看 2.1K关注 0票数 5

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

代码语言:javascript
复制
% java PasswdPrompt

但是当我调用控制台== null时,它会失败

代码语言:javascript
复制
% java PasswdPrompt | less

代码语言:javascript
复制
% java PasswdPrompt < inputfile

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

有人吗?

提前感谢

代码语言:javascript
复制
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.");
    }
}
EN

回答 2

Stack Overflow用户

发布于 2011-03-16 14:16:59

来自Java 文档页面:

如果System.console返回NULL,那么控制台操作是不允许的,这要么是因为操作系统不支持它们,要么是因为程序是在非交互式环境中启动的。

这个问题很可能是因为使用管道脱离了“交互式”模式,并且使用输入文件作为System.in使用,因此没有Console

** 更新 **

这是一个快速的解决办法。在main方法的末尾添加以下行:

代码语言:javascript
复制
if (args.length > 0) {
   PrintStream out = null;
   try {
      out = new PrintStream(new FileOutputStream(args[0]));
      out.print(passwd);
      out.flush();
   } catch (Exception e) {
      e.printStackTrace();
   } finally {
      if (out != null) out.close();
   }
}

并调用您的应用程序,如

代码语言:javascript
复制
$ java PasswdPrompt .out.tmp; less .out.tmp; rm .out.tmp

但是,提示密码将驻留在明文(尽管是隐藏的)文件中,直到命令终止为止。

票数 0
EN

Stack Overflow用户

发布于 2011-03-18 04:03:37

因此,由于某种原因,当System.console()返回null时,终端回显总是关闭的,所以我的问题变得微不足道。下面的代码完全符合我的要求。谢谢你的帮助。

代码语言:javascript
复制
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));
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5326406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档