可以获取当前正在运行的Java可执行文件的路径吗?

huangapple go评论69阅读模式
英文:

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

问题

假设我想从命令行运行一个Java程序,并使用以下命令:

myExes\java\java.exe AJavaProgram

如您所见,java.exe不在我的路径中,因此我是手动运行它,而不是简单地使用命令java AJavaProgram

我希望程序返回/打印命令中的第一个条目,在本例中,该条目是myExes\java(在这之后包括java.exe也可以)。

有没有办法做到这一点?

最初,我认为这很简单。args[0]应该返回路径,但事实并非如此。

英文:

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.

答案1

得分: 8

ProcessHandle.current() 返回当前的 Java 进程。您可以使用它来查看进程句柄信息中的完整命令:

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

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

答案2

得分: 1

你无法获取字符串"myExes\java\java.exe",但你可以获取Java安装的位置。

以下是在Windows 10上使用OpenJDK 14运行的结果:

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

输出

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

作为参考,java.exe的完整路径是:

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

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

答案3

得分: -2

这种方式怎么样?
您可以获取Java的主目录。

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

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

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

答案4

得分: -2

当您执行myExes\java\java.exe AJavaProgram时,AJavaProgram是传递给java.exe的参数,而不是反过来。当您执行java AJavaProgram时也是一样的,AJavaProgram是传递给java的参数。

英文:

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.

huangapple
  • 本文由 发表于 2020年5月29日 07:55:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/62076423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定