Java Console input(2009-12-08 11:13:28)
reproduced
Tags: gossip |
Category: Corejava |
0 Introduction
Reading data from the console is a relatively common feature, and implementations in previous versions of JDK 5.0 are more complex and require manual processing of the system's input stream. Interestingly, starting with the JDK version 5.0, the way to enter data from the console with each additional version number, there is a new method, which also increases the choice of the type, can be selected according to different requirements. Here's a look at how the data is read from the console and the pros and cons of each version.
1 methods read from JDK 1.4 and below
In JDK 1.4 and below, there is only one way to enter data from the console, using system.in to get the system's input stream, and then bridging to a character stream to read the data from the flow of characters. 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 ("Please enter string:");
System.out.println ( " Input of the ReadString method: "+ 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;
}
}
From the above code snippet, this console input method is very cumbersome, in order to be able to read the entire row of data, the use of the BufferedReader class for processing, and in the process of reading also need to capture IOException. However, this is the only way to read data from the console in JDK 1.4 and the following versions. Another way to read data from a non-console is to use the Joptionpane in Swing, which will pop up a very nice input dialog to let the user enter the data, but this is a more alternative approach, not recommended.
Import Javax.swing.JOptionPane;
public class Test2 {
public static void Main (string[] args ) {
String str = Readstringfromdialog ("Please enter a word String: ");
System.out.println ( " Input of the Readstringfromdialog method: "+ str";
}
private static string Readstringfromdialog (String prompt ) {
return joptionpane.showinputdialog (prompt);
}
}
Both methods have a common disadvantage-they can only read strings, and if they need to read other types of data, they need to be converted manually.
2 JDK 5.0 Read method
Starting with JDK 5.0, the Java.util.Scanner class is added to the base Class library, which, according to its API documentation, is a text scanner that uses regular expressions for basic types and string parsing. Using its scanner (InputStream source) construction method, you can pass in the input stream of the system system.in and read the data from the console. The sample code is as follows:
Import Java.util.Scanner;
public class Test3 {
public static void Main (string[] args ) {
string str = readString5 ("Please enter string:");
System.out.println ( " Input of the ReadString5 method: "+ str";
}
 
private static string ReadString5 (String prompt) {
scanner Scanner = new Scanner ( system.in);
System.out.print (prompt);
return Scanner.nextline ( );
}
}
from the code point of view, Test3 than Test1 a lot less code, the core code only two lines. In fact, it is not scanner console input to simplify, but in its internal implementation has been ioexception processing, and the use of InputStreamReader to a character a character to scan read (hey, it itself is a scanner), Just scanner did a higher-level package.
Scanner not only reads strings from the console, but also reads seven basic types and two large numeric types in addition to char, and does not need to be explicitly manually converted. Scanner not only scans the characters entered in the console, it also allows the read-in string to match a certain regular expression pattern, and throws a Inputmismatchexception exception if it does not match.
When using system.in as its construction parameter, it scans only the characters in the system input stream. It also has other constructs, can be scanned from a file or a string to parse the string, the specific use of the method can refer to the API documentation description.
3 JDK 6.0 Read method
Starting with JDK 6.0, the Java.io.Console class was added to the base class library to obtain character-based console devices associated with the current Java virtual machine. The data can be read more conveniently under the console interface of the pure character. The sample code is as follows:
Import Java.io.Console;
Import Java.util.Scanner;
public class Test4 {
public static void Main (string[] args) {
String str = ReadString6 ("Please enter string:");
SYSTEM.OUT.PRINTLN ("Input of the ReadString6 method:" + str);
}
private static string ReadString6 (String prompt) {
Console console = System.Console ();
if (console = = null) {
throw new IllegalStateException ("Cannot use console");
}
return Console.ReadLine (Prompt);
}
}
In Test1 and Test3, the prompt information before entering the data needs to be output using System.out.print (), but using the console-based Test4 class, you can put the prompt information directly in the method parameters.
If you need to enter sensitive information such as passwords in the console, displaying alternative characters like in a browser or in an application can be cumbersome prior to JDK 6.0 (see the article "Password masking in the Java programming language" for details), Instead of using the console class's Readpassword () method to enter a password explicitly on the console and save the result of the password in a char array, the API documentation suggests that the array should be emptied immediately after use to reduce the amount of time it takes in memory to enhance security.
However, the console also has some drawbacks, according to the CONSOLEAPI documentation:
Whether a virtual machine has a console depends on the underlying platform and how the virtual machine is called. If the virtual machine starts from an interactive command line and does not redirect the standard input and output streams, its console will be present and usually connected to the keyboard and displayed from where the virtual machine is launched. If the virtual machine is started automatically (for example, by the background job scheduler), it usually does not have a console.
As you can see from the documentation above, there is no way to get to the console instance with the IDE, because the standard input and output streams are redirected in the IDE's environment, and the input and output from the system console is redirected to the IDE's console. Therefore, this program cannot be used in the IDE, and Test1 and Test3 do not have this limitation.
4 Summary
The above includes a variety of Java versions from the console to read data from the method, the pros and cons of their analysis. Some suggestions for use are given below, for reference:
In the case of JRE 1.4 or below, there is no choice but to use the Test1 or non-console read-Test2 method.
In the case of JRE 5.0, it is recommended to use the scanner-based Test3 method for easier data reading.
In the case of JRE 6.0, and only when running under the console of the character interface, using the Test4 method, if you need to read sensitive data like passwords, you must use TEST4 or self-implementation for security reasons. If you need to read into a data type other than the string type, we recommend that you use scanner-based console input.
Source: >
From for notes (Wiz)
Java console input scanner, InputStreamReader, console description