System.console() returns null

后端 未结 12 873
有刺的猬
有刺的猬 2020-11-22 04:55

I was using readLine of BufferedReader to get input/new password from user, but wanted to mask the password so I am trying to use java.io.Con

相关标签:
12条回答
  • 2020-11-22 05:27

    This is a bug #122429 of eclipse

    0 讨论(0)
  • 2020-11-22 05:30

    According to the docs:

    If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

    0 讨论(0)
  • 2020-11-22 05:35

    Got this error message when running the application from Netbeans. Judging from the other answers, it seems this happens when running your application from an IDE. If you take a look at this question: Trying to read from the console in Java, it is because

    Most IDEs are using javaw.exe instead of java.exe to run Java code

    The solution is to use the command line/terminal to get the Console.

    0 讨论(0)
  • 2020-11-22 05:40

    If your IDE uses javaw instead of java, then this issue is bound to happen as javaw is essentially java without console window.

    0 讨论(0)
  • 2020-11-22 05:43

    This code snippet should do the trick:

    private String readLine(String format, Object... args) throws IOException {
        if (System.console() != null) {
            return System.console().readLine(format, args);
        }
        System.out.print(String.format(format, args));
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        return reader.readLine();
    }
    
    private char[] readPassword(String format, Object... args)
            throws IOException {
        if (System.console() != null)
            return System.console().readPassword(format, args);
        return this.readLine(format, args).toCharArray();
    }
    

    While testing in Eclipse, your password input will be shown in clear. At least, you will be able to test. Just don't type in your real password while testing. Keep that for production use ;).

    0 讨论(0)
  • 2020-11-22 05:43

    System.console() returns null if there is no console.

    You can work round this either by adding a layer of indirection to your code or by running the code in an external console and attaching a remote debugger.

    0 讨论(0)
提交回复
热议问题