3

My Jar file supports both being clicked, and launched from the command line.

I will only display the GUI if there is a graphics environment available by checking GraphicsEnvironment.isHeadless()

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

I have been unable to find an answer to this, are there any cross-platform environment variables, or anything else I can look at to know whether the user launched my program using java -jar app.jar, or whether they double clicked the .jar file?

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
  • I think you can check your args (in your main) and see whether '-jar app.jar' was passed. You have to check that, because I'm not certain – hellow Aug 13 '18 at 07:13
  • 1
    Nope.. those are JVM args. My args array will be empty in this example. – Matt Clark Aug 13 '18 at 07:14
  • 3
    Similar: [java check if jar was launched from command line or explorer](https://stackoverflow.com/questions/28132368/java-check-if-jar-was-launched-from-command-line-or-explorer) – Lino Aug 13 '18 at 07:15
  • possible duplicate: https://stackoverflow.com/questions/16610525/how-to-determine-if-graphicsenvironment-exists – Alan Deep Aug 13 '18 at 07:51
  • Thanks @AlanDeep, I know how to determine that... the link you posted is what I say I already use for this. Regardless of if the graphics environment exists or not, I want to know _how_ the binary was launched. – Matt Clark Aug 13 '18 at 07:52

1 Answers1

3

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

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 to run the code from the command line using the following command:

java -jar [your_runnable_file.jar]
Alan Deep
  • 2,037
  • 1
  • 14
  • 22
  • Using `JOptionPane.showMessageDialog(f, "Console is null.");`, this does actually appear to work as expected, at least in the environment I just tried it! _However in Eclipse it says there is no console, which there is._ – Matt Clark Aug 13 '18 at 08:15
  • `System#console` can be null while still being executed by another program. `java -jar file.jar` can be executed from an exe or even another jar file while the console object is null. therefore your method is flawed. It appears to be a java issue. they should have a javadoubleclick.exe which runs on double then adding a System.property("jar.doubleclicked") which returns true/false in a string form – nullsector76 Jul 26 '21 at 19:55