I was using readLine
of BufferedReader
to get input/new password from user, but wanted to mask the password so I am trying to use java.io.Console
class. Problem is that System.console()
returns null
when an application is debugged in Eclipse. I am new to Java and Eclipse not sure is this the best way to achieve? I am right clicking on the source file and selecting "Debug As" > "Java Application". Is there any workaround?
System. console() returns null if there is no console. You can work round this either by adding a layer of indirection to your code or by running the code in an external console and attaching a remote debugger.
The Java Console class is be used to get input from console. It provides methods to read texts and passwords. If you read password using Console class, it will not be displayed to the user.
The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.
This is a bug #122429 of eclipse
This code snippet should do the trick:
private String readLine(String format, Object... args) throws IOException { if (System.console() != null) { return System.console().readLine(format, args); } System.out.print(String.format(format, args)); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); return reader.readLine(); } private char[] readPassword(String format, Object... args) throws IOException { if (System.console() != null) return System.console().readPassword(format, args); return this.readLine(format, args).toCharArray(); }
While testing in Eclipse, your password input will be shown in clear. At least, you will be able to test. Just don't type in your real password while testing. Keep that for production use ;).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With