java.io.Console class in Java
The command-line environment that is often used to run programs is called a console. Though there are other methods for reading from and writing to the console, the Console
class in Java also provides some methods for it. This article explains the Console
class and the methods in it.
The class java.io.Console
The class Console
extends java.lang.Object
and implements the Flushable
interface,
public final class Console extends java.lang.Object implements Flushable
This class was first introduced in JDK version 6 that provides methods with which the character-based console device, if any, associated with the current Java Virtual Machine can be accessed. It is a convenience class because most of its functionalities are available through System.in
and System.out
. The class also provides a method for reading a password securely by not echoing it the console. The class is already internally attached to the system console.
The Console existence
The existence of the console depends upon the underlying platform and whether the virtual machine is invoked from an interactive command. If the virtual machine started automatically by a background job scheduler, then it will not have any console.
Accessing the Console
This class doesn’t provide a constructor. If a console exists, it is represented by a Console
class and it can be obtained by System.console()
method. null
will be returned upon invoking the method System.console()
if no console exists for that virtual machine. Read and write operations are synchronized. The read methods return a null
value if the end of the console input stream is reached. Unless specified otherwise, any method in this class will throw NullPointerException
if null
is passed as the argument.
The methods of Console class
public void flush()
Description
Flushes the console and forces any buffered output to be written immediately.
Usage
Console con = System.console(); con.flush();
public Console format(String fmt, Object... args)
Description
Writes a string to the console in the format specified by the format string.
Parameters
fmt
– This is a format string from the Format string syntax
args
– The Arguments referenced by the format specifiers in the format string. When there are more arguments than the format specifiers then the extra arguments will be ignored.
Returns
Console
Throws
IllegalFormatException
on violating the syntax of the format string fmt
, when the number of arguments is insufficient and when the format specifier doesn’t match the corresponding argument.
Usage
Console con = System.console(); con.format("%s", "Hello, World!");
public console printf(String fmt, Object... args)
Description
A convenience method to writing a string to the console in the format specified by the format string.
Parameters
fmt
– A format string in the Format string syntax
args
– This is the Arguments referenced by the format specifiers from the format string. When there are more arguments than the number of format specifiers, then extra arguments are ignored.
Returns
Console
Throws
IllegalFormatException
on violating the syntax of the format string fmt
, when the number of arguments is insufficient and when the format specifier doesn’t match the corresponding argument.
Usage
Console con = System.console(); con.printf("%s", "Hello, World!");
public Reader reader()
Description
Retrieves the unique Reader
object associated with the console. This method is for complex applications, where data of all types are read from the console. For simple applications that only read strings, it is recommended to use readLine
.
Returns
The Reader
associated with the console
Usage
Console con = System.console(); Scanner s = new Scanner(con.reader());
public String readLine()
Description
Reads a line of text from the console
Returns
A string containing only the text read from the console excluding any line termination characters or null
if the end of the line is reached.
Throws
IOError
when an I/O error occurs
Usage
Console con = System.console(); String s = con.readLine();
public String readLine(String fmt, Object... args)
Description
Prints a formatted output as a prompt and then reads a line of text from the console.
Parameters
fmt
– A format string in the Format string syntax
args
– This is the arguments referenced by format specifiers in the format string. If the number of arguments is more than the format specifiers, then the extra arguments are ignored.
Returns
A string containing only the text read from the console excluding any line termination characters or null
if the end of the line is reached.
Throws
IOError
when an I/O error occursIllegalFormatException
on violating the syntax of the format specifierfmt
, when the number of arguments is insufficient or the format specifier doesn’t match the corresponding argument.
Usage
Console con = System.console(); String name = con.readLine(); String username = con.readLine("Username for %s: ", name); System.out.println("Welcome, "+username);
public char[] readPassword()
Description
Reads a line of text from the console with echoing disabled.
Returns
- A character array only containing the text read from the console excluding any line termination characters or
null
when the end of the line is reached. - The character array can be cleared after use to minimize the lifetime of the sensitive information in memory.
Throws
IOError
when an I/O error occurs
Usage
Console con = System.console(); String username = con.readLine("Username: "); String password = new String(con.readPassword()); System.out.println("Welcome, "+username);
public char[] readPassword(String fmt, Object.. args)
Description
Prints a formatted string as a prompt and then reads a line of text from the console with echoing disabled.
Parameters
fmt
– A format string in the Format string syntax
args
– These are the arguments referenced that are by the format specifiers in the format string. If there are more arguments than the number of format specifiers, the extra arguments are then ignored.
Return
A character array only containing the text read from the console excluding any line termination characters or null
when the end of the line is reached.
Throws:
IOError
when an I/O error occurs
Usage
Console con = System.console(); String username = con.readLine("Username: "); String password = new String(con.readPassword("Password: ")); System.out.println("Welcome, "+username);
public PrintWriter writer()
Description
It retrieves the unique PrintWriter
object associated with the console.
Returns
The PrintWriter
associated with the console.
Usage
Console con = System.console(); PrintWriter p = con.writer();
A Simple Login Example using some of the above methods
import java.io.Console; class consoleExample { public static void main(String[] args){ Console con = System.console(); String username = con.readLine("Username: "); String password = new String(con.readPassword("Password for %s:",username)); if (password.compareTo("")!=0) con.printf("Welcome, %s", username); else con.format("Enter correct password for %s", username); con.flush(); } }
It produces the following output when the password is not empty
Username: anonymoususer Password for anonymoususer: Welcome, anonymoususer
And when the password is empty, it produces the following output
Username: anonymoususer Password for anonymoususer: Enter correct password for anonymoususer
Leave a Reply