代码示例
import java.io.Console;
import java.util.Scanner;
public class Demo {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("susername:");
String susername = scanner.nextLine();
System.out.println("spassword:");
String spassword = scanner.nextLine();
System.out.println("susername:" + susername + ",spassword:" + spassword);
Console console = System.console();
String cusername = console.readLine("cusername:");
char[] cpassword = console.readPassword("cpassword:");
System.out.println("cusername:" + cusername + ",cpassword:" + new String(cpassword));
}
}
区别说明
二者都能接收控制台的输入,不同点是Scanner接收的都是明文输入,Console可以接收密码的隐藏输入,Scanner可以在集成工具中输入,而Console不能,它只能用在标准输入、输出流未被重定向的原始控制台中使用,否则会报空指针异常。