如何使命令行下输入的东西变成*

来源:百度知道 编辑:UC知道 时间:2024/06/07 03:54:08
我用java编了一个输入输出的小东东,
import java.io.*;

public class MyfirstIo{
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

while(true) {
System.out.print("请输入> "); // prompt the user
System.out.flush(); // make the prompt appear now.
String sql = null;
try{
sql=in.readLine();
} catch(Exception e ){

}

// 如果用户输入 "quit"就退出
if ((sql == null) || sql.equals("quit")) break;

// 忽略空行
if (sql.length() == 0) continue;

//显示输入的内容
try {
System.out.println(sql);
} catch (Exception e) {
System.er

Java 里,图形界面的密码掩盖只不过是一行代码的功夫,
因为 JPasswordField 类提供了很直接的解决。(若使用 TextField 则需要两行代码。)
可惜 Java 并没有为命令行的密码掩盖提供任何直接的支持。

下面的代码里,PasswordField 类的 readPassword 方法通过 EraserThread 类提供这种服务。
readPassword 在用户输入密码之前启动 EraserThread,读了密码之后便马上停止该线程并返回密码。
EraserThread 运行的时候会尝试以每秒一千次的速度删除并用星号代替用户打出的每一个字符。

PasswordMasking 类里的 main 示范了 readPassword 的应用。

有疑问尽管问。

import java.io.*;

class PasswordMasking {
    public static void main(String argv[]) {
        String password = PasswordField.readPassword("Enter password: ");
        System.out.println("The password entered is: "+password);
    }
}

class PasswordField {

    /**
     *@param prompt The prompt to display to the user