Methods and advantages and disadvantages of reading data from the console in different Java versions

Source: Internet
Author: User

In Java, reading data from the console is a common function. The implementation in versions earlier than JDK 5.0 is complex and requires manual processing of system input streams. Since JDK 5.0, every time a version number is added to the method that can input data from the console, there is a new method, which also adds the selected type, you can choose based on different requirements. Next, let's take a look at the methods for reading data from the console of each version and their advantages and disadvantages.


1. How to read data from the console in 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 );

}

/**

* Use the system input stream to read data from the console

* JDK version used

* @ Param prompt information

* @ Return refers to 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 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, you also need to capture IOException 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.

The sample code is as follows:

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 );

}

/**

* In the JOptionPane input dialog box, enter a string.

* JDK version used

* @ Param prompt information

* @ Return refers to the input string.

*/

Private static String readStringFromDialog (String prompt ){

Return JOptionPane. showInputDialog (prompt );

}

}

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. How does JDK 5.0 read data from the console?

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. collections;

Public class Test3 {

Public static void main (String [] args ){

String str = readString5 ("Enter the String :");

System. out. println ("readString5 Method Input:" + str );

}

/**

* Use the Scanner class to read strings from the console

* Applicable to JDK 5.0 and later versions

* @ Param prompt information

* @ Return refers to the input string.

*/

Private static String readString5 (String prompt ){

Required bytes = new bytes (System. in );

System. out. print (prompt );

Return response. nextLine ();

}

}

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 handler to input the console, but the IOException has been processed in its internal implementation, moreover, InputStreamReader is used to scan and read a single character (it is itself 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. How does JDK 6.0 read data from the console?

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. collections;

Public class Test4 {

Public static void main (String [] args ){

String str = readString6 ("Enter the String :");

System. out. println ("readString6 Method Input:" + str );

}

/**

* Use the Console class to read strings from the Console

* Applicable to JDK 1.6 or later versions

* @ Param prompt information

* @ Return refers to the input string.

*/

Private static String readString6 (String prompt ){

Console 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, it is quite troublesome to display substitution characters like in a browser or application, before JDK 6.0, the readPassword () method of the Console class can be used to enter the password without explicit display on the Console and save the password result in the char array. According to the suggestions in the API documentation, after use, the array should be cleared immediately 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.


Summary: in the case of JDK 1.4 or below, you have no choice but to use Test1 or Test2 that is not read on the console;

In the case of JDK, we recommend that you use the Test3 method based on objective to facilitate data reading;

JDK 6.0 is used only when running on the Character interface console. If you need to read sensitive data such as passwords, test4 must be used for security consideration or self-implemented;

If you want to read data types other than the string type, we recommend that you use the token-based console.

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.