Why does System.console() return null for a command line app? [duplicate]

会有一股神秘感。 提交于 2019-12-08 05:34:22

问题


I am working on a legacy app which depends on user command line input:

String key = System.console().readLine("Please enter the license key: ");

However, I am getting a NullPointerException because System.console() gives me a null.

Why does System.console() return null for a command line app? It happens when running it out of the terminal as well as IDE.


回答1:


If you start java from a terminal window, then it really should work, even though I haven't tried on OSX.

If you run a simple test using java directly from the terminal, does it work?

echo 'public class Test { public static void main(String[] args) {System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test 

Expected output:

hello world

If it doesn't work, then sorry, no console support on your platform.

However, if it works, and your program doesn't then there is a problem with how your program is started.

Check how the java binary started? Is it started from a shell script? Check that stdin/stdout have not been redirected or piped into something, and possibly also that it's not started in the background.

ex: This will probably make System.console() return null.

java Test | tee >app.log    

and this:

java Test >/tmp/test.log

This seems to work on my machine (linux)

java Test &

Neither does it seem as if System.setOut, System.setErr or System.setIn affects the console, even after a couple of gc's and finalizers.


However:

Closing (the original) System.out or System.in will disable the console too.

echo 'public class Test { public static void main(String[] args) {System.out.close();System.console().printf("hello world%n");}}' >Test.java && javac Test.java && java Test 

Expected output:

Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:1)

So; scan your code for places where it closes streams, or passes System.out somewhere it might get closed.




回答2:


To read from Standard input (command line input) you must use some kind of stream reader to read the System.in stream. An InputStreamReader initialised by

    InputStreamReader(System.in) 

lets you read character by character. However, I suggest wrapping this with a BufferedReader:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String inputLine = reader.readLine();

Must import

    java.io.*;


来源:https://stackoverflow.com/questions/20982664/why-does-system-console-return-null-for-a-command-line-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!