如何禁用控制台回显
How to disable console echoing
我正在编写一个命令行程序,它使用 println 以非常特定的格式显示文本。我遇到的问题是,每次我要求用户通过 Scanner.nextLine() 输入内容时,控制台会自动在控制台中回显他们的输入。有没有办法禁止控制台立即显示用户输入的文本?如果重要的话,我是 运行 Linux.
从版本 6 开始,您可以使用 Java 附带的控制台 class 和 readPassword() 方法。该方法禁用回显,但只读取必须转换为任何字符的数组你需要:
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();
我正在编写一个命令行程序,它使用 println 以非常特定的格式显示文本。我遇到的问题是,每次我要求用户通过 Scanner.nextLine() 输入内容时,控制台会自动在控制台中回显他们的输入。有没有办法禁止控制台立即显示用户输入的文本?如果重要的话,我是 运行 Linux.
从版本 6 开始,您可以使用 Java 附带的控制台 class 和 readPassword() 方法。该方法禁用回显,但只读取必须转换为任何字符的数组你需要:
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();