简体   繁体   中英

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

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?

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 describedhere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM