Java – Is my jar double-clicked or started from the command line?

Is my jar double-clicked or started from the command line?… here is a solution to the problem.

Is my jar double-clicked or started from the command line?

My jar file supports click and launch from the command line.

If there is a graphical environment available

by checking GraphicsEnvironment.isHeadless(),

I will only show the GUI

I would like to be able to print logs to a file on disk when the user double-clicks the jar file, and print them to the console when launched from the command line.

I

haven’t been able to find an answer to this question, are there any cross-platform environment variables, or anything else I can look at to know if the user is using java -jar app .jar or if they double-clicked on the .jar file?

Solution

One way to do this is to determine when the console is empty:

public static void main(String[] args) {
    Console console = System.console();
    if(console!=null){
        System.out.println("Console is not null");
    }else{
        System.out.println("Console is null");
    }
}

Try running the code from the command line using the following command:

java -jar [your_runnable_file.jar]

Related Problems and Solutions