gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:38:34 24 4
gpt4 key购买 nike

I have tried the following codes both have different approaches.

Approach 1: It breaks when executing in the latest version of Eclipse IDE say 2020-03 whereas it works fine in Mars IDE.

This problem is already asked on this How to display asterisk for input in Java?.

方法一:


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("\010*");

try {
Thread.sleep(1);
} catch (InterruptedException ie) {
ie.printStackTrace();
}

}
}

public void stopMasking() {
this.stop = true;
}
}

方法 2:

It does not work on Eclipse IDE but does work on the command line.


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 上的初始 boolean 值更改为 false,然后在 catch 后告诉将其设置为 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 将使您的程序陷入困境。希望有帮助!

关于java - 用户在控制台输入密码时,显示星号(*)而不是纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61003404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com