如果从 Windows 环境变量 PATH 启动,如何在 Java 中获取可执行文件的完整路径?

How to get the full path of an executable in Java, if launched from Windows environment variable PATH?

如果可执行文件保存在 Windows 环境变量 PATH.[=22 的一部分的位置,我想获取在 Java 中启动的可执行文件的路径=]

例如,我们使用以下代码片段在 windows 中启动 NOTEPAD。这里 notepad.exe 保存在 Windows 文件夹下,该文件夹是 Windows 环境变量 PATH 的一部分。所以这里不需要给出可执行文件的完整路径。

Runtime runtime = Runtime.getRuntime();         
Process process = runtime.exec("notepad.exe");

所以我的问题是,如何在 Java 程序中获取 executables/files 的绝对位置(在这种情况下,如果 notepad.exe 保存在 c:\windows 下,在里面java 程序我需要获取路径 c:\windows),如果它们是从 PATH 个位置像这样启动的?

您可以通过以下方式在 Windows 中获取可执行文件的位置:

where <executable_name>

例如:

where mspaint returns:

C:\Windows\System32\mspaint.exe

以及以下代码:

Process process = Runtime.getRuntime().exec("where notepad.exe");
try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
    File exePath = new File(in.readLine());
    System.out.println(exePath.getParent());
}

将输出:

C:\Windows\System32

没有内置函数可以执行此操作。但是您可以像 shell 在 PATH.

上找到可执行文件一样找到它

拆分PATH变量的值,遍历条目,应该是目录,第一个包含notepad.exe的是使用的可执行文件。

public static String findExecutableOnPath(String name) {
    for (String dirname : System.getEnv("PATH").split(File.pathSeparator)) {
        File file = new File(dirname, name);
        if (file.isFile() && file.canExecute()) {
            return file.getAbsolutePath();
        }
    }
    throw new AssertionError("should have found the executable");
}