How To Accept Password From Console in Java

By Angsuman Chakraborty, Gaea News Network
Thursday, January 12, 2006

Finally you can easily accept password from console in Java, without echoing them.

This long unmet need has been addressed in JDK 1.6 codeline.

A new class - java.io.Console has been defined to handle console I/O.

To accept password from console in JDK 6.0 (aka JDK 1.6) use either:
public char[] readPassword()
or
public char[] readPassword(String fmt, Object… args)

Sample code:
  Console cons;
  char[] passwd;
  if ((cons = System.console()) != null &&
       (passwd = cons.readPassword("[%s]", "Password:")) != null) {
       // Use the passwd for authentication etc.
       ....; // Your code
       // After you are done zero the character array in memory for reducing security risk
      java.util.Arrays.fill(passwd, ' ');
 }

So could I entice you yet to download JDK 1.6?

Discussion

balamurugan
March 28, 2008: 6:46 am

it,s very nice


lisa19860622
November 19, 2007: 7:46 pm

Console c = System.console();

if(c != null){
String user = new String(c.readLine(”Enter user:”));
String pwd = new String(c.readPassword(”Enter pwd:”));

c.printf(”%20s”,user);
c.printf(”\n%20s\n”,pwd);

}else
System.out.println(”Console is unavailable”);

注意運行環境為:jdk1.6+jcreator3.5.
如果jcreator4.0的話,得到的c總是null.


moulali
June 8, 2006: 6:21 am

thanks for the service you provided to me.

January 12, 2006: 10:45 am

[...] India Fourth Largest Internet User How To Accept Password From Console in Java » JDK1.6 / JDK 6.0 Downloaded? January 12th, 2006 by AngsumanChakraborty [...]

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :