ConsoleDemo.java
Download ConsoleDemo.java
1: // ConsoleDemo - This class shows how to use a Console object for
2: // I/O. Console is an alternative to using System.in and System.out,
3: // but depending on how the program was run, there may be no console
4: // available. Additionally, this code shows how to use Console to
5: // read in a password from a console program, which won't echo the
6: // password entered.
7: // The JVM throws an IO error if you try this with standard input
8: // redirected from someplace unreadable; try " ... < NUL" on Windows.
9: //
10: // Written 12/2012 by Wayne Pollock, Tampa Florida USA
11: // Based on the example code in the Java docs.
12:
13: import java.io.Console;
14: import java.util.Arrays;
15:
16: public class ConsoleDemo {
17: public static void main ( String [] args ) {
18:
19: Console con = System.console();
20: if ( con == null )
21: throw new UnsupportedOperationException( "No Console Available" );
22:
23: con.printf( "Username: " );
24: String userName = con.readLine(); // doesn't include any EOL characters
25:
26: // Read in password, with no echo:
27: final char [] enteredPassword = con.readPassword( "Password: " );
28:
29: if ( enteredPassword == null ) {
30: con.printf( "Incorrect password\n" );
31: } else {
32: final char [] actualPassword = "secret".toCharArray();
33: if ( Arrays.equals( actualPassword, enteredPassword ) )
34: con.printf( "Welcome %s!%n", userName );
35: else
36: con.printf( "Incorrect password\n" );
37:
38: // In any case, need to erase the passwords from memory now:
39: Arrays.fill( enteredPassword, '\0' );
40: // This is pointless; *never* hardcode passwords in your code!
41: Arrays.fill( actualPassword, '\0' );
42: }
43: }
44: }