How Java reads data from the console

Source: Internet
Author: User
Tags command line documentation readline regular expression versions

Reading data from the console is a more common feature, and implementation in the previous version of JDK 5.0 is more complex and requires manual processing of the system's input stream. Interestingly, starting with JDK 5.0, the method of entering data from the console has a new method for each additional version number, which also increases the type of selection that can be chosen based on different requirements. Let's look at how each version reads data from the console and their pros and cons.

1 methods read by JDK 1.4 and the following versions

The only way to enter data from the console in the JDK 1.4 and below is to use system.in to get the system's input stream, and then bridge to the 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 a string:");

SYSTEM.OUT.PRINTLN ("Input of the ReadString method:" + str);

}

/**

* Read data from the console using the system's input stream

* For the JDK version used

* @param prompt prompt information

* @return The input string

*/

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 code snippet above, this type of console input is very cumbersome, in order to be able to read the entire row of data, using the BufferedReader class for processing, and in the process of reading also need to capture IOException. But this is JDK 1.4. And the only way to read data from the console in the following version. Another way to read data in a non-console is to use the Joptionpane in Swing, which will pop up a very beautiful input dialog box to allow users to enter 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 string:");

SYSTEM.OUT.PRINTLN ("Input of the Readstringfromdialog method:" + str);

}

/**

* Using the Joptionpane Input dialog box, enter the string

* For the JDK version used

* @param prompt prompt information

* @return The input string

*/

private static string Readstringfromdialog (String prompt) {

return Joptionpane.showinputdialog (Prompt);

}

}

Both of the above methods have a common disadvantage--only the strings can be read, and if you need to read other types of data, you need to convert them 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 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 a string:");

SYSTEM.OUT.PRINTLN ("Input of the ReadString5 method:" + str);

}

/**

* Read strings from the console using the Scanner Class (Scanner)

* Applicable to JDK 5.0 and later versions

* @param prompt prompt information

* @return The input string

*/

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 to simplify the console input, but in its internal implementation has been ioexception processing, and the use of InputStreamReader to a character for scanning read (hey, it itself is a scanner), Just scanner to do a higher level of encapsulation.

Scanner not only can read strings from the console, but can also read seven basic types and two large numeric types other than char, and do not need to explicitly hand-convert them. Scanner not only scans the characters entered in the console, it also allows the read 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's input stream. It also has other constructs that can be scanned for parsing strings from files or strings, which can be referenced using the API documentation.

3 JDK 6.0 Read method

Starting with JDK 6.0, the Java.io.Console class is added to the base Class library to obtain a character-based console device that is associated with the current Java virtual organization. The data can be read more conveniently under the console interface of a 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 a string:");

SYSTEM.OUT.PRINTLN ("Input of the ReadString6 method:" + str);

}

/**

* Read a string from the console using the Console Class (console)

* Applicable to JDK 1.6 or later version

* @param prompt prompt information

* @return The input string

*/

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 hint information before entering data needs to be System.out.print (), but using the console based Test4 class, you can put the hint information directly in the method parameters.

If you need to enter sensitive information such as passwords in a console, as in a browser or an application, it is quite cumbersome to do so before JDK 6.0 (you can refer to the password mask in the Java programming language). The Readpassword () method using the console class can then explicitly enter the password on the console and save the password results in a char array, and, based on the recommendation of the API documentation, empty the array immediately after use to reduce the 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 invoked. If the virtual machine starts from an interactive command line and does not redirect the standard input and output streams, its console will exist and is typically connected to the keyboard and displayed where the virtual machine is started. If the virtual machine is started automatically (for example, started by the background job scheduler), it usually does not have a console.

As you can see from the documentation above, you cannot get to the console instance with the IDE, because in the IDE's environment, the standard input and output streams are redirected and the input 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 have no such limitations.

4 Summary

These include methods for reading data from the console in Java, and their pros and cons are analyzed. Some suggestions for use are given below, which can be used for reference:

In the case of JRE 1.4 or below, there is no choice but to use a Test1 or Test2 method that is read-only by the console.

In the case of JRE 5.0, it is recommended that you use a scanner-based Test3 method for more convenient data reading.

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 such as passwords, you must use TEST4 for security considerations or for your own implementation. If you need to read a data type other than the string type, it is recommended that you use scanner console input.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.