masking pasword in eclipse IDE java by bypassing the eclipse bug for console.readPassword()

Viewed 256

im trying to mask password when i type my user input password it must be hidden or *. im using this readPassowrd method which has issues like null pointer error for performing the task in IDE but fine for Command line. Is there anyways i can mask password in IDE only.

this is what i have below

char[] PASSWORD =console.readPassword("ENTER YOUR PASSWORD :");
log.info("Entered" + PASSWORD);

but i get Exception in thread "main" java.lang.NullPointerException in console in the IDE.

Any help with this ?

2 Answers

It is well known that java.io.Console is NOT actually available always, but it depends by the implementation of your runtime environment.
Normally, it's hard to find an IDE which provides an instance of Console class, that's why you get NullPointerException, simply because when you launch your application with the IDE's "Run" command, the System.console() method returns null.
I am afraid this is not an issue of Eclipse, but it happens with IntelliJ and many other IDEs as well.

Personally, if I need to use the Console, what I normally do is to launch the application via the Terminal, because the JVM launched via java command it always returns a not-null instance of java.io.Console, so you can also test the readPassword method.
You can launch the terminal in Eclipse by right-clicking on output folder of your application and then select the menu "Show In -> Terminal", then you can launch the classic "java" command (hope you know how it works):

> java -cp . <YourMainClass>

You can try this:

Console cnsl = null;
  
try {
   // creates a console object
   cnsl = System.console();

   // if console is not null
   if (cnsl != null) {
      // read password into the char array
      char[] pwd = cnsl.readPassword("Password: ");
      
      // prints
      System.out.println("Password is: "+pwd);
   } 
   
} catch(Exception ex) {
   // if any error occurs
   ex.printStackTrace();      
}

As it is described here

Related