[英]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:假设我想从命令行运行 java 程序并使用以下命令:
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
.如您所见, java.exe 不在我的路径中,所以我手动运行它,而不是简单地使用命令
java AJavaProgram
。
I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java
.我希望程序返回/打印命令中的第一个条目,在这种情况下,该条目是
myExes\java
。 (Including java.exe at the end of this is also fine). (包括最后的java.exe也可以)。
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.
args[0] 将返回路径,但事实并非如此。
ProcessHandle.current() returns the current Java process. ProcessHandle.current()返回当前 Java 进程。 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.无法获取字符串
"myExes\java\java.exe"
,但可以获取 Java 安装的位置。
The following are results for running with OpenJDK 14 on Windows 10:以下是在 Windows 10 上使用 OpenJDK 14 运行的结果:
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("sun.boot.library.path"));
Output Output
C:\prog\Java64\jdk-14
C:\prog\Java64\jdk-14\bin
For reference, the full path of java.exe
is:作为参考,
java.exe
的完整路径为:
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.当您执行
myExes\java\java.exe AJavaProgram
AJavaProgram
,它是java.exe
的参数,而不是相反。 Its the same when you do java AJavaProgram
, AJavaProgram
is the arg to java
.当您执行
java AJavaProgram
时,它是相同的, AJavaProgram
是java
的参数。
How about this way?这条路怎么样?
You can get a java home dir.您可以获得 java 主目录。
String path = System.getProperty("java.home");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.