Console classes in Java 6.0

Started by thiruvasagamani, Aug 30, 2008, 11:00 AM

Previous topic - Next topic

thiruvasagamani

Console is a new class which is included in JAVA SE 6. It is the advanced alternative to the Standard Streams. It is a single, predefined object of Console type that provide most of the same features as by Standard Streams, and others besides. The Console is particularly useful for secure password entry. The Console object provides input and output streams which is true character stream.

Before using the Console, you must retrieve the Console object by invoking System.console(). This method returns the object if it is available. But if it returns NULL then Console operations are restricted because the OS doesn't support them or the program was executed in non-interactive environment.

Through the readPassword method, the Console object support secure password entry. This method helps in two ways.

1. The password is not visible on the screen.

2. The "readPassword" returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

The Following program is for changing the user's password and the following code demonstrates several Console methods:

import java.io.Console;

import java.util.Arrays;

import java.io.IOException;

public class UseConsole

{

  static char [] oldPass;

  public static void main (String args[]) throws IOException

   {

    Console c = System.console();

    if (c == null)

    {

     System.err.println("Console Object is not available.");

     System.exit(1);

    }

   String login = c.readLine("Enter your login Name: ");

   oldPass = c.readPassword("Enter your Existing password: ");

   if (check(login, oldPass))

    {

     boolean flag;

     do



char [] newPass1 = c.readPassword("Enter your new password: "); 

char [] newPass2 = c.readPassword("Enter new password again: "); 

flag = !Arrays.equals(newPass1, newPass2);

if (flag)

{

c.format("Mismatch the Passwords. Please try again.%n");

}   

else

{

change(newPass1);

c.format("Password for %s has changed.%n", login);

}

Arrays.fill(newPass1, ' ');

Arrays.fill(newPass2, ' ');

} while (flag);

}

}

//check method.

static boolean check(String login, char[] password) {

return true;

}

//change method.

static void change(char[] password) {

oldPass=password;

}

}
Thiruvasakamani Karnan