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

王朝知道·作者佚名  2010-08-26
窄屏简体版  字體: |||超大  
 
分類: 電腦/網絡 >> 程序設計 >> 其他編程語言
 
問題描述:

我用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;

}

}

小贴士:① 若网友所发内容与教科书相悖,请以教科书为准;② 若网友所发内容与科学常识、官方权威机构相悖,请以后者为准;③ 若网友所发内容不正确或者违背公序良俗,右下举报/纠错。
 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航