有两种方法可以实现,一种是使用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();
}
}
}
……