Chapter: Java The Complete Reference - The Java Library - Input/Output: Exploring java.io

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

The Console Class - java.io

The Console class was added to java.io by JDK 6. It is used to read from and write to the console, if one exists. It implements the Flushable interface.

The Console Class

 

The Console class was added to java.io by JDK 6. It is used to read from and write to the console, if one exists. It implements the Flushable interface. Console is primarily a convenience class because most of its functionality is available through System.in and System.out. However, its use can simplify some types of console interactions, especially when reading strings from the console.

Console supplies no constructors. Instead, a Console object is obtained by calling System.console( ), which is shown here:

 

static Console console( )

 

If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible.

Console defines the methods shown in Table 20-5. Notice that the input methods, such as readLine( ), throw IOError if an input error occurs. IOError is a subclass of Error. It indicates an I/O failure that is beyond the control of your program. Thus, you will not normally catch an IOError. Frankly, if an IOError is thrown while accessing the console, it usually means there has been a catastrophic system failure.

Also notice the readPassword( ) methods. These methods let your application read a password without echoing what is typed. When reading passwords, you should "zero-out" both the array that holds the string entered by the user and the array that holds the password that the string is tested against. This reduces the chance that a malicious program will be able to obtain a password by scanning memory.




Table 20-5   The Methods Defined by Console

 

Here is an example that demonstrates the Console class:

 

// Demonstrate Console.

import java.io.*;

 

class ConsoleDemo {

 

public static void main(String args[]) { String str;

 

Console con;

 

    //Obtain a reference to the console.

    con = System.console();

 

    //If no console available, exit.

 

    if(con == null) return;

 

    //Read a string and then display it.

 

    str = con.readLine("Enter a string: ");

 

con.printf("Here is your string: %s\n", str);

 

}

 

}

 

Here is sample output:

 

Enter a string: This is a test.

 

Here is your string: This is a test.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.