Java console input sample share

  • 2020-04-01 03:04:40
  • OfStack

There are several methods for Java console input

1. How to read JDK 1.4 and the following versions

The only way to enter data from the console in JDK 1.4 and later 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 character stream. Only strings can be read, and manual conversion is required to read other types of data. The code is 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. How to read JDK 5.0

Starting with JDK 5.0, the base class library added the java.util.scanner class, which, according to its API documentation, is a text Scanner that USES regular expressions for basic types and string analysis. Using its Scanner(InputStream source) construction method, the InputStream system.in of the System can be passed in and the data can be read from the console. Canner can read not only strings from the console, but also seven basic types other than char and two large numeric types without explicitly converting them manually. The code is as follows:


Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(str);

3. How to read JDK 6.0

Starting with JDK 6.0, the java.io.console class was added to the base class library to get a character-based Console device associated with the current Java virtual authority. Data can be read more easily in a pure character console interface. The code is as follows:


Console console = System.console();
if (console == null)
{
    throw new IllegalStateException(" Cannot use console ");
}
String str = console.readLine("console");
System.out.println(str);


Related articles: