有兩種方法可以實現,一種是使用jni調c程序(這個我還沒試過),另一種就是純java的實現方式(不過可能會有點閃爍). 原理很簡單,就是另外啟動一個線程,不停的寫提示輸入密碼,而主線程負責讀密碼.
public class CTest implements Runnable { Thread thread = null; public boolean flag = false; public static void main(String s[]) { try { StringBuffer password = new StringBuffer(); CTest c = new CTest(); c.test();
while(true) { char cc = (char)System.in.read(); c.flag = true; if(cc != '\r' && cc != '\n') { password.append(cc); }
if(cc == '\n') { break; } } System.out.println("Your password is:" + password.toString()); } catch(Exception e ) { System.out.println(e); } }
public void run() { while(!flag) { try { System.out.print("\r" + "Please enter your password:" + " \r" ); thread.sleep(10); } catch(Exception e) {} } }
public void test() throws Exception { if(thread==null) { thread=new Thread(this); thread.start(); } }
}
|