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条回答
Anthone
2楼-- · 2020-01-22 12:16

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.

查看更多
闹够了就滚
3楼-- · 2020-01-22 12:18

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.

查看更多
闹够了就滚
4楼-- · 2020-01-22 12:20

I refered&used formixian's answer shown above. The point is use (black) cmd console to run your Java program as "ojonugwa ochalifu" suggested.

**

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

I believe that in the run configurations for Eclipse, you can configure whether to assign a console or not - ensure this is checked. (It's been a while since I used Eclipse so I can't give specific instructions I'm afraid).

If that doesn't work, then something that will definitely do this job is starting your application in debug mode, then connect to the process with Eclipse. Search for "eclipse remote debugging" if you're not sure how to do this.

Furthermore, in general it is a bad idea to require a console to be assigned as this very much impacts the flexibility of your application - as you've just discovered. Many ways of invoking Java will not assign a console, and your application is unusable in these instances (which is bad). Perhaps you could alternatively allow arguments to be specified on the command line. (If you're testing the console input specifically then fair enough, but it would potentially be useful for people to be able to invoke your application from scripts and/or on headless servers, so this sort of flexible design is almost always a good idea. It often leads to better-organised code, too.)

查看更多
霸刀☆藐视天下
6楼-- · 2020-01-22 12:28

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.

查看更多
登录 后发表回答