javacmd

Find out if Java program is running from CMD or not


I want to write a Java program that receives input through text (a console program).
When this program starts up, straight away in the main method, I want to be able to check if the program was started from a Command Prompt (cmd) or from a JAR file. This is so that I can open a JFrame to receive input if there is no cmd to receive it.

Essentially, something like this:

public static void main(String[] args){
    if(startedFromCmd()) {
        startProgram();
    } else{
        openInputFrame();
        startProgram();
    }
}

Is there any built-in Java method which can check this?


Solution

  • You can use System.console() which returns a console object if there is one attached to the Java Virtual Machine.

    The method returns null if there is no console attached. Note that this is not 100% reliable. E.g. the method returns null for the internal console in the Eclipse IDE (which is actually bug #122429). It works with the Windows command line though.

    An example could look like this:

    public static void main(String[] args)
    {
        if (System.console() != null)
        {
            System.out.println("There is a console!");
        }
        else
        {
            JFrame frame = new JFrame("There is no console!");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(100, 100);
            frame.setVisible(true);
        }
    }
    

    Running this in the Windows command line with java -jar MyJar.jar will result in

    There is a console!

    being printed on the console.

    Double clicking the .jar-file will show a JFrame.