屏蔽从控制台输入的密码:Java如何从控制台输入掩码密码?我正在使用Java 6。我尝试过使用console.readPassword(),但它不起作用。一个完整的例子可能对我有帮助。这是我的代码:import java.io.BufferedReader;import java.io.Console;import java.io.IOException;import java.io.InputStreamReader;public class Test {
public static void main(String[] args)
{
Console console = System.console();
console.printf("Please enter your username: ");
String username = console.readLine();
console.printf(username + "\n");
console.printf("Please enter your password: ");
char[] passwordChars = console.readPassword();
String passwordString = new String(passwordChars);
console.printf(passwordString + "\n");
}}我得到一个NullPointerException ...
3 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
一个完整的例子?运行此代码:(注意:此示例最好在控制台中运行,而不是在IDE中运行,因为在这种情况下System.console()方法可能会返回null。)
import java.io.Console;public class Main { public void passwordExample() { Console console = System.console(); if (console == null) { System.out.println("Couldn't get Console instance"); System.exit(0); } console.printf("Testing password%n"); char[] passwordArray = console.readPassword("Enter your secret password: "); console.printf("Password entered was: %s%n", new String(passwordArray)); } public static void main(String[] args) { new Main().passwordExample(); }}
温温酱
TA贡献1752条经验 获得超4个赞
Console console = System.console();String username = console.readLine("Username: ");char[] password = console.readPassword("Password: ");
添加回答
举报
0/150
提交
取消