Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.console() returns null

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?

like image 719
Gauls Avatar asked Nov 17 '10 10:11

Gauls


People also ask

Why does system console return null?

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.

What is System console in Java?

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.

What is console readLine in Java?

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.


2 Answers

This is a bug #122429 of eclipse

like image 82
swimmingfisher Avatar answered Sep 29 '22 11:09

swimmingfisher


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

like image 31
formixian Avatar answered Sep 29 '22 11:09

formixian