当用户在控制台上输入密码时,显示星号(*)符号而不是纯文本



我尝试过以下代码,它们都有不同的方法。

方法1:它在最新版本的Eclipse IDE中执行时会中断,比如2020-03,而在MarsIDE中运行良好。

这个问题已经在"如何在Java中显示输入星号?"中提出了?。

方法1:


Package test;
import java.io.*;
public class Test {
public static void main(final String[] args) {
String password = PasswordField.readPassword("Enter password:");
System.out.println("Password entered was:" + password);
}
}
class PasswordField {
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();
}
et.stopMasking();
return password;
}
}
class EraserThread implements Runnable {
private boolean stop;
public EraserThread(String prompt) {
System.out.print(prompt);
}
@SuppressWarnings("static-access")
public void run() {
while (!stop) {
System.out.print("10*");
try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void stopMasking() {
this.stop = true;
}
}

方法2:

它不在Eclipse IDE上工作,但在命令行上工作。


import java.io.Console;
public class Main {
public void passwordExample() {        
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}

方法1的程序不起作用,因为橡皮擦线程似乎没有关闭。您应该将stopMasking的初始布尔值更改为false,然后在捕获后将其设置为true。代码中有许多资源可以做到这一点。我发现最好的是在这里:

http://www.cse.chalmers.se/edu/year/2018/course/TDA602/Eraserlab/pwdmasking.html

这在我的Eclipse 2020构建中运行。至于您的第二种方法,控制台不适用于IDE中的用户输入,因此存在问题,但没有来自命令行的问题。如果你想使用这个版本,你可以用扫描仪代替控制台:

import java.util.Scanner
Scanner input = new Scanner(System.in);
String password = input.nextLine();
//implementation

我还建议导入您需要的特定类文件。导入所有java.io会使程序陷入困境。希望能有所帮助!

最新更新