Java控制台下密码的输入
时间:2014-03-19 12:05:12
收藏:0
阅读:496
一直以为java在控制台下输入密码是没有办法隐藏密码的,但是昨天在做一个抢课程序时去google了一下,原来在jdk1.6中加入了java.io.Console类,可以不回显的输入密码,使用起来也是非常的方便.
大家可以看出最终的一个就是readLine(true)函数了,这里面根本没有对单个字符输入进行操作的方法,所以感觉要达到输入一个字符显示一个*号大概需要从输入流开始入手.
下面看一下下面的代码:
import java.io.Console;
public class Main {
public static void main(String[] args){
Console console = System.console();
String password ;
password = new String(console.readPassword());
System.out.println("password="+password);
}
}程序运行后,输入字符没有显示,回车后,打印出结果.如下图
看到这里,大家可能都希望能够输入一个字符,显示一个星号之类的,这样有一定的提示作用.于是我查看了Console的源码,发现通过Console是实现不了的
public char[] readPassword() {
return readPassword("");
}
public char[] readPassword(String fmt, Object ... args) {
char[] passwd = null;
synchronized (writeLock) {
synchronized(readLock) {
try {
echoOff = echo(false);
} catch (IOException x) {
throw new IOError(x);
}
IOError ioe = null;
try {
if (fmt.length() != 0)
pw.format(fmt, args);
passwd = readline(true);
} catch (IOException x) {
ioe = new IOError(x);
} finally {
try {
echoOff = echo(true);
} catch (IOException x) {
if (ioe == null)
ioe = new IOError(x);
else
ioe.addSuppressed(x);
}
if (ioe != null)
throw ioe;
}
pw.println();
}
}
return passwd;
}
大家可以看出最终的一个就是readLine(true)函数了,这里面根本没有对单个字符输入进行操作的方法,所以感觉要达到输入一个字符显示一个*号大概需要从输入流开始入手.
原文:http://blog.csdn.net/dliyuedong/article/details/21456325
评论(0)