Saturday, 4 October 2014

Console

The class java.io.Console can be used to write Java programs which can interact with users via command line.

About java.io.Console:
  • read and write operations are synchronized to guarantee the atomic completion of critical operations, 
  • a "Console" instance is represented by a unique instance which can be obtained by invoking the "System.console()" method. If no console device is available then an invocation of that method will return null, 
  • if the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

    
  // We get a user's login and password 
  // and then we display the given values
  // We get an unique instance of "Console"
    Console console = System.console();

    // If this JVM has a console
    if(console != null){

      // We get a user's login
        String userLogin = console.readLine("Your login: ");

        // We get a user's password without displaying the typed characters
        char[] charUserPassword = console.readPassword("Your password: ");

        // We convert the returned array of characters to a String
        String userPassword = new String(charUserPassword);     

        // We display the given values
        System.out.println("Your login is '"+userLogin+"' and your password is '"+userPassword+"'.");
  }

Output (the characters in italic are the one given by a user; you noticed that the password is hidden):

    Your login: alex
    Your password:
    Your login is 'alex' and your password is 'toto'.

Important methods:

Method
Description
String userInput readLine(String prompt, Object... args)
Displays a prompt an returns a user's input as a String.
String userInput readLine()
Same than readLine(String prompt, Object... args), expect that there is not a prompt.
char[] userInput readPassword(String prompt, Object... args)
Displays a prompt an returns a user's input an array of characters. The difference with readLine() is that this method hides the user's input.
char[] userInput readPassword()
Same than readPasword(String prompt, Object... args), expect that there is not a prompt.
Reader reader()
Retrieves the unique Reader object associated with this console.
PrintWriter writer()
Retrieves the unique PrintWriter object associated with this console.