System.console() returns null

2020-01-22 12:01发布

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.Console class. Problem is that System.console() returns null when an application is debugged in Eclipse. I am new to Java and Eclipse not sure is this the best way to achieve? I am right clicking on the source file and selecting "Debug As" > "Java Application". Is there any workaround?

11条回答
可以哭但决不认输i
2楼-- · 2020-01-22 12:09

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 ;).

查看更多
叼着烟拽天下
3楼-- · 2020-01-22 12:09

I also ran into this problem when trying to write a simple command line application.

Another alternative to creating your own BufferedReader object from System.in is to use java.util.Scanner like this:

import java.util.Scanner;

Scanner in;
in = new Scanner(System.in);

String s = in.nextLine();

Of course this will not be a drop-in replacement to Console, but will give you access to a variety of different input functions.

Here's more documentation on Scanner from Oracle.

查看更多
贼婆χ
4楼-- · 2020-01-22 12:11

This is a bug #122429 of eclipse

查看更多
smile是对你的礼貌
5楼-- · 2020-01-22 12:12

That is right.

You will have to run the application outside of Eclipse. Look at the launcher configuration panels within Eclipse and see if you can spot the option that says to run the command in a separate JVM.

查看更多
Emotional °昔
6楼-- · 2020-01-22 12:12

add -console in your program arguments to start OSGi console

查看更多
兄弟一词,经得起流年.
7楼-- · 2020-01-22 12:14

According to the API:

"If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console."

查看更多
登录 后发表回答