问题
I'm writing a command line program that makes use of println to display text in a very specific format. The problem I encounter is that every time I ask the user to enter something via Scanner.nextLine(), the console automatically echos their input in the console. Is there a way to disable the console from immediately displaying the user's entered text? In case it matters, I am running Linux.
回答1:
You can use the Console class and readPassword() method that comes with Java since version 6. That method disable the echo, but only reads array of chars that you must convert to whatever you need:
Console console = System.console();
if (console == null) {
System.out.println("Console not active!");
System.exit(0);
}
System.out.print("Type something, please: ");
// This won't echo anything
char[] userInput = console.readPassword();
来源:https://stackoverflow.com/questions/32545424/how-to-disable-console-echoing