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()
| |
PrintWriter writer()
|