Receiving characters from the keyboard in Java
1. JDK 1.4 and earlier versions
In JDK 1.4 and earlier versions, there is only one way to input data from the console, that is, to use system. In to obtain the input stream of the system, and then bridge to the slave stream to read data from the slave stream. The sample code is as follows:
Import Java. io. ioexception; import Java. io. inputstreamreader; public class test1 {public static void main (string [] ARGs) {string STR = readstring ("Enter the string:"); system. out. println ("readstring Method Input:" + Str);} Private Static string readstring (string prompt) {bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); string STR = NULL; try {system. out. print (prompt); STR = BR. readline ();} catch (ioexception e) {e. printstacktrace () ;}return STR ;}}
Main Code
Bufferedreader BR = new bufferedreader (New inputstreamreader (system. In ));
String STR = Br. Readline ();
System. Out. println (STR );
From the code segment above, this type of console input method is very troublesome. In order to be able to read the entire row of data, bufferedreader class is used for processing, in addition, the ioexception must be captured during the read process. However, this is the only way to read data from the console in JDK 1.4 and earlier versions. Another non-console-based Data Reading method is to use joptionpane in swing to bring up a very beautiful input dialog box for users to input data. However, this is an alternative method, it is not recommended.
Import javax. swing. joptionpane; public class Test2 {public static void main (string [] ARGs) {string STR = readstringfromdialog ("Enter the string:"); system. out. println ("input of the readstringfromdialog method:" + Str);} Private Static string readstringfromdialog (string prompt) {return joptionpane. showinputdialog (prompt );}}
Main Code
String STR = joptionpane. showinputdialog ("Enter the string :");
System. Out. println (STR );
The preceding two methods share a common drawback: they can only read strings. If you want to read other types of data, you need to manually convert them.
2. JDK 5.0 reading Method
The Java. util. Classes class has been added to the basic class library of JDK 5.0. According to its API documentation, this class is a text scanner that uses regular expressions for basic types and string analysis. Using its internal (inputstream source) constructor, you can pass in the system input stream system. In And read data from the console. The sample code is as follows:
Import Java. util. secret; public class test3 {public static void main (string [] ARGs) {string STR = readstring5 ("Enter the string:"); system. out. println ("input of the readstring5 method:" + Str);} Private Static string readstring5 (string prompt) {repeated bytes = new bytes (system. in); system. out. print (prompt); return response. nextline ();}}
Main Code
Required bytes = new bytes (system. In );
String STR = response. nextline ();
System. Out. Print (STR );
In terms of code quantity, test3 has much less code than test1, and there are only two lines of core code. In fact, it is not simplified for the hacker to input the console, but ioexception has been processed in its internal implementation, and inputstreamreader is used to scan and read one character by one character (hey, it itself is a scanner), but the scanner is encapsulated at a higher level.
Explain not only reads strings from the console, but also seven other basic types and two large numeric types besides char, without explicit manual conversion. The parser can not only scan the characters entered in the console, but also allow the read string to match a certain regular expression pattern. If it does not match, an inputmismatchexception is thrown.
When system. In is used as its construction parameter, it only scans characters in the system input stream. It also has other structures that can scan and analyze strings from files or strings. For specific usage instructions, see the API documentation.
3. JDK 6.0 reading Method
The Java. Io. Console class has been added to the basic class library of JDK 6.0 to obtain the character-based console device associated with the current Java virtual machine. On the character-only console interface, you can easily read data. The sample code is as follows:
Import Java. io. console; import Java. util. secret; public class test4 {public static void main (string [] ARGs) {string STR = readstring6 ("Enter the string:"); system. out. println ("readstring6 Method Input:" + Str);} Private Static string readstring6 (string prompt) {console = system. console (); If (console = NULL) {Throw new illegalstateexception ("console unavailable");} return console. readline (prompt );}}
In test1 and test3, the system is required for the prompt information before entering the data. out. print ();, but use the console-based test4 class, you can directly put the prompt information in the method parameters.
If you need to enter password and other sensitive information in the console, display the replacement characters as in your browser or application, the practice before JDK 6.0 was quite troublesome (For details, refer to password shielding in Java programming language), and use readpassword () in the console class () you can enter the password in the console and save the password result in the char array. According to the suggestions in the API documentation, the array should be cleared immediately after use, to reduce the time it takes in the memory, so as to enhance security.
However, the console also has some disadvantages, as described in the consoleapi documentation:
Whether a virtual machine has a console depends on the underlying platform and the method of calling the virtual machine. If a virtual machine starts from an interactive command line without redirecting standard input and output streams, its console will exist and is usually connected to the keyboard and displayed from where the virtual machine starts. If the VM is automatically started (for example, started by the background Job scheduler), it usually does not have a console.
The preceding document shows that the console instance cannot be obtained when IDE is used because the standard input and output streams are redirected in the IDE environment, that is, the system console redirects the input and output to the IDE console. Therefore, this program cannot be used in IDE, and test1 and test3 do not have this restriction.
4. Summary
The methods for reading data from the console in various Java versions are described above, and their advantages and disadvantages are analyzed. The following are some suggestions for use:
In JRE 1.4 or earlier versions, you have no choice but to use the test1 method or the Test2 method that is not read from the console.
In JRE 5.0, we recommend that you use the test3 method based on objective to facilitate data reading.
In JRE 6.0, test4 is used only when running on the Character interface console. If you need to read sensitive data such as passwords, test4 must also be used for security considerations. If you want to read data types other than the string type, we recommend that you enter