Java console input has the following methods:
1. How to read JDK 1.4 and below
In JDK 1.4 and below, there is only one way to input data from the console, which is to use System.in to obtain the system's input stream, and then bridge to the character stream to read data from the character stream. Only strings can be read. If you need to read other types of data, you need to convert it manually. The code is as follows:
Copy the code code as follows:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try
{
str = br.readLine();
System.out.println(str);
}
catch (IOException e)
{
e.printStackTrace();
}
2. JDK 5.0 reading method
Starting from JDK 5.0, the java.util.Scanner class has been added to the basic class library. According to its API documentation, this class is a text scanner that uses regular expressions for basic type and string analysis. Using its Scanner(InputStream source) constructor, you can pass in the system's input stream System.in and read data from the console. Canner can not only read strings from the console, but also seven other basic types and two large number types in addition to char, without the need for explicit manual conversion. The code is as follows:
Copy the code code as follows:
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(str);
3. JDK 6.0 reading method
Starting from JDK 6.0, the java.io.Console class has been added to the basic class library, which is used to obtain the character-based console device associated with the current Java virtual machine. Data can be read more easily under the pure character console interface. The code is as follows:
Copy the code code as follows:
Console console = System.console();
if (console == null)
{
throw new IllegalStateException("Cannot use console");
}
String str = console.readLine("console");
System.out.println(str);