简体   繁体   中英

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.

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));

You can't get the string "myExes\java\java.exe" , but you can get the location of the Java installation.

The following are results for running with OpenJDK 14 on Windows 10:

System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("sun.boot.library.path"));

Output

C:\prog\Java64\jdk-14
C:\prog\Java64\jdk-14\bin

For reference, the full path of java.exe is:

C:\prog\Java64\jdk-14\bin\java.exe

When you do myExes\java\java.exe AJavaProgram AJavaProgram is the arg to java.exe and not the reverse. Its the same when you do java AJavaProgram , AJavaProgram is the arg to java .

How about this way?
You can get a java home dir.

String path = System.getProperty("java.home");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM