在Java中,我们可以使用System.console()
从控制台读取输入。
JavaSample.java
package com.mkyong.io;
import java.io.Console;
public class JavaSample {
public static void main(String[] args) {
// jdk 1.6
Console console = System.console();
System.out.print("Enter your name: ");
String name = console.readLine();
System.out.println("Name is: " + name);
System.out.print("Enter your password: ");
// Reads a password from the console with echoing disabled
char[] password = console.readPassword();
String passwordStr = String.valueOf(password); // char[] to String;
System.out.println("Password is: " + passwordStr);
}
}
输出量
Enter your name: mkyong
Name is: mkyong
Enter your password:
Password is: 123456
System.console()
在IDE中返回null,请尝试在控制台或终端中运行它。
$ cd project/target/classes
project/target/classes$ java com.mkyong.io.JavaSample
Enter your name: mkyong
Name is: mkyong
Enter your password:
Password is: 123456
参考文献
翻译自: https://mkyong.com/java/java-how-to-read-input-from-system-console/