Friday, November 6, 2009

Uses of Console class in Java

Java 6 introduce a new class Console in the family of java.io.
This Class is used to access the character-based console device, if any, associated with the current Java virtual machine.

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

If virtual machine has a console then it is represented by a unique instance of this class, which can be obtained by invoking
System.console().
If JVM does not recognize any console, then this function returns null.

The methods in this class are synchronized. You can read line of text by using the
readLine()
method. You can also read secure data such as Password by using
readPassword()
method. You can also format text by using
format()
. You can get PrintWriter and PrintReader by using
reader(), writer()
method.

Example: Get user name and password from the user.

public class IConsole
{
public static void main(String arg[])
{
Console console = System.console();
if(console!=null)
{
String userName = console.readLine("User Name:");
char [] password = console.readPassword("Password:");
console.printf("User Name is %1$s , Password is %1s",userName, String.valueOf(password));
}
}
}

3 comments:

  1. Which version of jdk will be required to use Console Class?

    ReplyDelete
  2. What is the difference between %1$s and %1s to print a string value?
    [ex. console.printf("User Name is %1$s , Password is %1s",userName, password);]

    ReplyDelete
  3. I think, console.readPassword() returns char[], not String. Please add this correction in the given program.

    ReplyDelete