Search code examples
javacommand-linesystem-properties

Can I get the path of the currently running java executable?


Suppose I want to run a java program from the command line and I use this command:

myExes\java\java.exe AJavaProgram

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.


Solution

  • ProcessHandle.current() returns the current Java process. You can use that to see the full command in the process handle’s info:

    ProcessHandle.current().info().command().ifPresent(
        cmd -> System.out.println(cmd));