Alan Bateman

Main | Next day (Oct 22, 2005) »

http://blogs.sun.com/alanb/date/20051021 Friday October 21, 2005

java.io.Console is finally here!

One of the most popular feature requests for J2SETM in recent times has been the request to improve console support and provide a way to enter passwords with echo disabled. Developers know this feature 4050435 as it has been skulking in the Top 25 RFEs list for some time.

The good news is that the feature has made it into Mustang thanks to Xueming Shen. It went into b57 and should show up be on the download site later today. The feature adds java.io.Console which provides methods to read lines and passwords from the console. It also provides useful methods to write formatted strings to the console too. Here's a little taster that prompts user to enter a password that is at least 8 characters in length. The password is not echoed to the console as it is entered.


static final int MIN_PASSWORD_LENGTH = 8;

char[] password;
do {
    password = System.console().readPassword(
      "Enter password (minimum of %d characters): ", MIN_PASSWORD_LENGTH);
} while (password.length < MIN_PASSWORD_LENGTH);


System.console() is used to obtain the unique Console for the Java virtual machine. There may not be a console of course - it depends on the platform, and also on how the Java virtual machine was started. If there isn't a console then the console() method returns null (the above code fragment doesn't check for this).

The readPassword method writes the prompt and reads the password. The prompt is provided as a format string and an argument list. If you've used the formatted printing support that was added in J2SE 5.0 then you'll recognize this.

Another thing about this code fragment is that it leaves you with a password in a character array. As with anything sensitive you don't want to have this in memory for a long time so it's good to zero the array as soon as you can.

So if you develop applications that need to access a character based console then you should find java.io.Console very useful (and very simple to use).


Valid HTML! Valid CSS!

This is a personal weblog, I do not speak for my employer.