Java如何实现用户输入密码时显示星号(*)并将密码存储为String类型
Java控制台输入密码显示星号实现方案
Java可以实现控制台输入密码时显示星号并存储为String类型,两种常见实现方案如下:
方案1:JDK自带无回显实现(兼容性最好)
该方案使用JDK1.6及以上版本内置的java.io.Console类,无需引入第三方依赖,虽然没有星号展示,但输入时不会显示任何明文,是绝大多数官方工具的标准密码输入实现。
import java.io.Console; public class Log_in_form { public static void main(String[] args) { String username = "rosas"; String correctPassword = "sandy"; Console console = System.console(); if (console == null) { System.out.println("当前环境不支持控制台交互,请在系统终端中运行程序"); return; } System.out.println("Enter username"); String user = console.readLine(); System.out.println("Enter password"); // readPassword返回char数组,直接转为String即可存储使用 char[] passwordChars = console.readPassword(); String pass = new String(passwordChars); if(user.equals(username) && pass.equals(correctPassword)){ System.out.println("Log in success"); } else { System.out.println("log in failed"); } } }
注意:该实现仅支持系统原生控制台,IDEA、Eclipse等IDE的内嵌控制台会获取不到console实例,打包为jar后在cmd/系统终端运行即可正常使用。
方案2:带星号回显的实现
如果必须要显示星号遮挡效果,需要自行逐字符处理键盘输入,同时兼容退格等交互逻辑,实现代码如下:
import java.io.IOException; import java.util.Scanner; public class Log_in_form { public static void main(String[] args) throws IOException, InterruptedException { String username = "rosas"; String correctPassword = "sandy"; System.out.println("Enter username"); Scanner scan = new Scanner(System.in); String user = scan.next(); System.out.println("Enter password"); String pass = readPasswordWithAsterisk(); if(user.equals(username) && pass.equals(correctPassword)){ System.out.println("\nLog in success"); } else { System.out.println("\nlog in failed"); } } // 自定义读取密码并显示星号的方法 private static String readPasswordWithAsterisk() throws IOException, InterruptedException { StringBuilder password = new StringBuilder(); // 关闭控制台默认回显,兼容Windows和Unix系系统 if (System.getProperty("os.name").startsWith("Windows")) { new ProcessBuilder("cmd", "/c", "echo off").inheritIO().start().waitFor(); } else { new ProcessBuilder("sh", "-c", "stty -echo").inheritIO().start().waitFor(); } try { int ch; while ((ch = System.in.read()) != '\n' && ch != '\r') { if (ch == '\b' || ch == 127) { // 处理退格键逻辑 if (password.length() > 0) { password.deleteCharAt(password.length() - 1); // 清除已显示的星号 System.out.print('\b'); System.out.print(' '); System.out.print('\b'); } } else { password.append((char) ch); System.out.print('*'); } } } finally { // 恢复控制台默认回显 if (System.getProperty("os.name").startsWith("Windows")) { new ProcessBuilder("cmd", "/c", "echo on").inheritIO().start().waitFor(); } else { new ProcessBuilder("sh", "-c", "stty echo").inheritIO().start().waitFor(); } } return password.toString(); } }
注意:该实现同样需要在系统原生终端运行,IDE内嵌控制台可能无法正常关闭回显,导致星号效果失效。
内容的提问来源于stack exchange,提问作者user15438289
相关产品推荐
相关产品推荐

