如果想在控制台上获取输入的字符直接用Scanner类就行了,但是不适合用来输入密码。如果想要输入密码,可以通过System.console()静态方法获取Console实例,Console提供以下几个方法来获取用户输入:
// 不带提示词
public String readLine(){...}
public char[] readPassword() {...}
// 带有提示词
public String readLine(String fmt, Object... args){...}
public char[] readPassword(String fmt, Object... args) {...}注意:这些方法不能再IDE中使用,因为IDE(如 IDEA、Eclipse)的 “运行控制台” 本质是模拟终端,并非系统原生控制台(System Console),因此System.console()会返回null,调用其方法时会触发空指针异常。
实例:
import java.io.Console;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Console console = System.console();
if (console != null) {
char[] password = null;
try {
String username = console.readLine("Username: ");
password = console.readPassword("Password: ");
System.out.printf("Hello, %s!\nYour password is %s%n", username, new String(password));
} finally {
// 关键:使用后强制清空密码数组,彻底销毁内存中的密码痕迹
if (password != null)
Arrays.fill(password, '\0'); // 将数组所有元素替换为空字符
}
} else {
System.out.println("No console");
}
}
}
评论