How to handle java passwd reading when System.console() returns null?

不想你离开。 提交于 2019-12-05 10:09:02

From the Java documentation page :

If System.console returns NULL, then Console operations are not permitted, either because the OS doesn't support them or because the program was launched in a noninteractive environment.

The problem is most likely because using a pipe falls out of "interactive" mode and using an input file uses that as System.in, thus no Console.

** UPDATE **

Here's a quick fix. Add these lines at then end of your main method :

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

And invoke your application like

$ java PasswdPrompt .out.tmp; less .out.tmp; rm .out.tmp

However, your prompted password will reside in plaintext (though hidden) file until the command terminates.

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!