Console
# Console
有时候,我们需要输入密码,此时如果用 System.in 会让密码明文显示到控制台上;而 Console 类能隐式输入密码。
# Console.readPassword()
我们可以用 Console.readPassword()
方法:
import java.io.Console;
public class Main {
public static void main(String[] args) throws Exception {
Console cnsl = System.console();
if (cnsl != null) {
String alpha = cnsl.readLine("Name: ");
System.out.println("Name is: " + alpha);
char[] pwd = cnsl.readPassword("Password: ");
System.out.println("Password is: " + pwd);
}
}
}
package chapter11;
import java.io.Console;
public class IODemo13Console {
public static void main(String[] args) {
Console cnsl = System.console();
if (cnsl != null) {
String alpha = cnsl.readLine("Name: ");
System.out.println("Name is: " + alpha);
char[] pwd = cnsl.readPassword("Password: ");
System.out.println("Password is: " + pwd);
}else {
System.out.println("Please run in terminal, not in IDE ");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
运行结果:
D:\Projects\LearnJavaSE\src> javac ./chapter11/IODemo13Console.java
PS D:\Projects\LearnJavaSE\src> java chapter11.IODemo13Console
Name: PeterJXL
Name is: PeterJXL
Password:
Password is: PeterJXL
1
2
3
4
5
6
2
3
4
5
6
第 3 行:输入 Name 的时候,输入什么,命令行里就回显什么;
第 5 行:输入 Password 的时候,并没有在命令行里回显我输入的字符;
注意,得在命令行里运行,不能在 IDE 里运行。在 IDE 里运行的话获取不了对象,导致 NPE,可以参考:
Beware though, this doesn't work (opens new window) with the Eclipse console. You'll have to run the program from a true console/shell/terminal/prompt to be able to test it.
java - Hide input on command line - Stack Overflow (opens new window)
# 参考
上次更新: 2024/10/1 15:49:31