Console提供了三种读取输入的方式:
String readLine()- 从控制台读取一行文本。char[] readPassword()- 在禁用回显的情况下从控制台读取密码或者加密文本Reader reader()- 检索与此控制台关联的Reader对象。该阅读器应该由复杂的应用程序使用。例如,“Scanner”对象利用底层“Reader”之上的丰富解析/扫描功能。
使用 readLine() 读取用户输入
Console console = System.console();
if(console == null) {
System.out.println("在当前JVM进程中, 控制台不可用");
return;
}
String userName = console.readLine("Enter the username: ");
System.out.println("Entered username: " + userName);
程序输出
Enter the username: jackli Entered username: jackli
使用 readPassword() 读取用户输入
Console console = System.console();
if(console == null) {
System.out.println("在当前JVM进程中, 控制台不可用");
return;
}
char[] password = console.readPassword("Enter the password: ");
System.out.println("Entered password: " + new String(password));
程序输出
Enter the password: // 因为是密码,输入不可见 Entered password: passphrase
使用 reader() 读取用户输入
Console console = System.console();
if(console == null) {
System.out.println("在当前JVM进程中, 控制台不可用");
return;
}
Reader consoleReader = console.reader();
Scanner scanner = new Scanner(consoleReader);
System.out.println("Enter age:");
int age = scanner.nextInt();
System.out.println("Entered age: " + age);
scanner.close();
程序输出
Enter age: 12 Entered age: 12
日期:2020-09-17 00:09:33 来源:oir作者:oir
