在控制臺程序中輸入密碼,而不會顯示出密碼
發(fā)表時間:2023-08-03 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]有兩種方法可以實(shí)現(xiàn),一種是使用jni調(diào)c程序(這個我還沒試過),另一種就是純java的實(shí)現(xiàn)方式(不過可能會有點(diǎn)閃爍).原理很簡單,就是另外啟動一個線程,不停的寫提示輸入密碼,而主線程負(fù)責(zé)讀密碼.pu...
有兩種方法可以實(shí)現(xiàn),一種是使用jni調(diào)c程序(這個我還沒試過),另一種就是純java的實(shí)現(xiàn)方式(不過可能會有點(diǎn)閃爍).
原理很簡單,就是另外啟動一個線程,不停的寫提示輸入密碼,而主線程負(fù)責(zé)讀密碼.
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();
}
}
}