Console class will considerably simplify reading the data from the console and writing the data on the console.
If the JVM is invoked indirectly by IDE, or if the JVM is invoked from a background process, then the method call System.console() will fail and return null.
Formatted I/O with the Console Class
The Console class supports formatted I/O in the methods printf() and format() plus the overloaded methods of readPassword() and readLine().
Login.java
package com.appfworks.io;
/**
* Created by suresh on 30/10/15.
*/
import java.io.Console;
import java.util.Arrays;
// code to illustrate the use of readPassword method
class Login {
public static void main(String []args) {
Console console = System.console();
if(console != null) {
String userName = null;
char[] password = null;
userName = console.readLine("Enter your username: ");
// typed characters for password will not be displayed in the screen
password = console.readPassword("Enter password: ");
// password is a char[]: convert it to a String first before comparing contents
if(userName.equals("scrat") && new String(password).equals("nuts")) {
// we're hardcoding username and password here for
// illustration, don't do such hardcoding in pratice!
console.printf("login successful!");
}
else {
console.printf("restart application and try again");
}
// "empty" the password since its use is over
Arrays.fill(password, ' ');
}
}
}
No comments:
Post a Comment