晋江高分古言宠文推荐:如何使命令行下输入的东西变成*

来源:百度文库 编辑:高校问答 时间:2024/04/29 20:08:47
我用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.err.println("Exception: " + e.getMessage()+ ":" +
e.toString());
}

} //end while

} //end main
}

我想在输入的时候字符都变成*,比如我要输入密码了,显示出来不太好,请问该如何做?

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
     *@return The password as entered by the user
     */
    public static String readPassword (String prompt) {
        EraserThread et = new EraserThread(prompt);
        Thread mask = new Thread(et);
        mask.start();

        BufferedReader in =
            new BufferedReader(new InputStreamReader(System.in));
        String password = "";

        try {
            password = in.readLine();
        } catch (IOException ioe) {
         ioe.printStackTrace();
        }
        // stop masking
        et.stopMasking();
        // return the password entered by the user
        return password;
    }
}

class EraserThread implements Runnable {
    private boolean stop;

    /**
     *@param The prompt displayed to the user
     */
    public EraserThread(String prompt) {
         System.out.print(prompt);
    }

    /**
     * Begin masking...display asterisks (*)
     */
    public void run () {
        stop = true;
        while (stop) {
            System.out.print("\010*");
            try {
                Thread.currentThread().sleep(1);
            } catch(InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }

    /**
     * Instruct the thread to stop masking
     */
    public void stopMasking() {
        this.stop = false;
    }
}

VB里把Passwordchar设为*就行了呀
Java那么难?!