屏蔽从控制台输入的密码

屏蔽从控制台输入的密码

本文介绍了屏蔽从控制台输入的密码:Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道一种方法来从控制台输入屏蔽密码?我使用Java 6。

Does anyone know of a way to mask a password from console input? I'm using Java 6.

我试过使用console.readPassword(),但它不会工作...一个完整的例子可能会帮助我。

I've tried using console.readPassword(), but it wouldn't work... A full example might help me actually.

这是我的代码:

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test
{
    public static void main(String[] args)
    {
        Console console = System.console();

        console.printf("Please enter your username: ");
        String username = console.readLine();
        console.printf(username + "\n");

        console.printf("Please enter your password: ");
        char[] passwordChars = console.readPassword();
        String passwordString = new String(passwordChars);

        console.printf(passwordString + "\n");
    }
}

我得到一个NullPointerException ....

I'm getting a NullPointerException....

提前感谢! :)

推荐答案

完整的例子?运行此代码:(注意:此示例最好在控制台中运行,而不是在IDE中运行,因为System.console()方法可能在这种情况下返回null。)

A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)

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();
}
}

这篇关于屏蔽从控制台输入的密码:Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:25