Linux 拨号vps windows公众号手机端

java如何将登录密码改为星号

lewis 8年前 (2017-07-14) 阅读数 8 #程序编程
文章标签 Java

要将登录密码改为星号,可以使用Java的Console类来实现。Console类提供了readPassword()方法,该方法可以隐藏用户输入的密码并以字符数组的形式返回。

以下是示例代码:

import java.io.Console;

public class PasswordExample {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("Console is not available");
            System.exit(1);
        }

        char[] passwordArray = console.readPassword("Enter your password: ");
        String password = new String(passwordArray);

        System.out.println("Your password is: " + password);

        // 清除密码
        Arrays.fill(passwordArray, ' ');
    }
}

在示例代码中,首先检查console对象是否为空,以确保程序在非交互式环境下也可以运行。然后使用console.readPassword()方法隐藏用户输入的密码,并将其存储在字符数组passwordArray中。然后将字符数组转换为字符串,并输出密码。最后,使用Arrays.fill()方法清除密码数组,以确保密码不再占用内存。

请注意,使用Console类获取密码比使用Scanner类更安全,因为Console类不会在控制台上显示密码。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门