I am writing a command line program that asks for a password, and I do not want it to execute a local echo of password characters. After some searching, I came across System.console().readPassword() , which seems great, except when it comes to pipes on Unix. So, my sample program (below) works fine when I call it like:
% java PasswdPrompt
but with Console == null error when I call it like
% java PasswdPrompt | less
or
% java PasswdPrompt < inputfile
IMHO, this seems like a JVM problem, but I can't be the only one that has run into this problem, so I have to imagine that there are some simple solutions.
Any?
Thank you in advance
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."); } }
source share