如何禁用控制台回显 [英] How to disable console echoing

查看:73
本文介绍了如何禁用控制台回显的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个命令行程序,它利用 println 以非常特定的格式显示文本.我遇到的问题是,每次我要求用户通过 Scanner.nextLine() 输入内容时,控制台会自动在控制台中回显他们的输入.有没有办法禁止控制台立即显示用户输入的文本?以防万一,我正在运行 Linux.

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.

推荐答案

您可以使用自 Java 6 版起随附的 Console 类和 readPassword() 方法.该方法禁用回显,但仅读取您输入的字符数组必须转换为您需要的任何内容:

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();

这篇关于如何禁用控制台回显的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆