Java控制台readPassword()返回无意义的字符

时间:2012-12-30 21:55:55

标签: java io passwords

Java的Console对象存在一个荒谬的困难,尤其是readPassword()方法。

我有当前代码读取密码,两次,并循环,直到两个密码相同:

do {
    dbPasswordOne = userInput.readPassword("Enter a password for the bookstall: ");
    System.out.println(dbPasswordOne.toString());
    dbPasswordTwo = userInput.readPassword("Re-enter the password: ");
    System.out.println(dbPasswordTwo.toString());
} while (!Arrays.equals(dbPasswordOne, dbPasswordTwo));

在我看来,这应该可以正常工作(打印只是出于调试目的。但是,这是我在Linux终端中获得的输出:

Enter a password for the bookstall: 
[C@9e4acce
Re-enter the password: 
[C@40d0d75

每次运行它时,它总是相同的两个无意义的字符串,无论我输入什么。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:9)

您正在toString()上致电char[]。自动装箱char[],你看到的字符串就是它的参考名称。您必须将char[]转换为String

尝试System.out.println(new String(dbPasswordOne));

答案 1 :(得分:2)

请勿使用dbPasswordTwo.toString() toString(),因为这会打印出引用名称。只需删除toString()

<PrintWriter System.out println(char[])有一个toString()方法,然后调用。这会打印出每个字符,并且不会隐式调用{{1}}方法。

答案 2 :(得分:1)

这是一个完整的示例,改编自我怀疑您可能正在使用的“Console.readPassword()”示例:

/*
 * REFERENCE:
 * http://www.java2s.com/Tutorial/Java/0120__Development/Readpasswordfromconsole.htm
 *
 * SAMPLE OUTPUT:
 * Enter your login: abc
 * Enter your old password:
 * You entered: def...
 */
import java.io.Console;
import java.io.IOException;
import java.util.Arrays;

public class X {

  public static void main(String args[]) throws IOException {

    Console c = System.console();
    if (c == null) {
      System.err.println("No console.");
      System.exit(1);
    }

    String login = c.readLine("Enter your login: ");
    char[] oldPassword = c.readPassword("Enter your old password: ");

    String sPassword = new String(oldPassword);
    System.out.println ("You entered: " + sPassword + "...");
  }
}

注意第String sPassword = new String(oldPassword);行。这会将char []数组转换为可打印的字符串。

'希望有所帮助!