如何从控制台输入中屏蔽密码?我正在使用Java 6。
我尝试使用console.readPassword(),但无法使用。一个完整的例子可能实际上对我有帮助。
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 ...
NullPointerException ...
一个完整的例子?运行以下代码:(注意:此示例最好在控制台中运行,而不是从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(); } }