New Features of JDK 6 7: using the console to develop console programs Java. io. the console class is dedicated to accessing character-based console devices. if your program needs to interact with cmd in Windows or terminal in Linux, you can use the console class. however, we cannot always get the available console. Whether a JVM has an available console depends on the underlying platform and how the JVM is called. if the JVM is started in interactive command line (such as Windows cmd) and the input and output are not redirected to another place, an available console instance can be obtained. the following code demonstrates the usage of the console class: /** * @ Author chinajash */ Public class consoletest {
Public static void main (string [] ARGs ){ Console console = system. Console (); // obtain the console instance If (console! = NULL) {// determines whether the console is available String user = new string (console. Readline ("enter user:"); // read the entire line of Characters String Pwd = new string (console. readpassword ("Enter passowrd:"); // read the password. It is not displayed when the password is entered. Console. printf ("user is:" + User + "/N "); Console. printf ("password is:" + PWD + "/N "); } Else { System. Out. println ("console is unavailable "); } } } If you run the above program in netbean5.5 Console is unavailable Indicates that the console is unavailable because the JVM is not called in the command line or the input and output are redirected. however, if we run the above Program (Java consoletest) in the command line, the program can obtain the console instance and execute the following: Enter User: chinajash Enter passowrd: User is: chinajash Password is: chinajash Here we can see that when you enter the password, the console does not display these password characters, but the program can get the entered password string, which is the same as entering the password in Linux. |