title: How to handle java passwd reading when System.console() returns null?
body: <p>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 <code>System.console().readPassword()</code>, which seems great, <em>except</em> when dealing with pipes in Unix.  So, my example program (below) works fine when I invoke it as:</p>
  
  <pre><code>% java PasswdPrompt
  </code></pre>
  
  <p>but fails with Console == null when I invoke it as</p>
  
  <pre><code>% java PasswdPrompt | less
  </code></pre>
  
  <p>or</p>
  
  <pre><code>% java PasswdPrompt &lt; inputfile
  </code></pre>
  
  <p>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.</p>
  
  <p>Any one?</p>
  
  <p>Thanks in advance</p>
  
  <pre><code>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.");
      }
  }
  </code></pre>