Console Support in Java 6.0


The coolest feature in Java 6.0 is IO Support. One of the most popular feature requests for J2SE in recent times has been the request to improve console support and provide a way to enter passwords with echo disabled.

also read:

One new class is provided:
Console – Contains methods to access a character-based console device. The readPassword() methods disable echoing thus they are suitable for retrieval of sensitive data such as passwords. The method System.console() returns the unique console associated with the Java Virtual Machine.

The feature adds which provides methods to read lines and passwords from the console. It also provides useful methods to write formatted strings to the console too. The following example shows 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 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.

There is also 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 need to have this in memory for a long time so it’s good to zero the array as soon as you can. So for developing applications that need to access a character based console then you should find and very simple to use.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!