【问题标题】:How to get the full path of an executable in Java, if launched from Windows environment variable PATH?如果从 Windows 环境变量 PATH 启动,如何获取 Java 中可执行文件的完整路径?
【发布时间】:2015-12-25 22:49:46
【问题描述】:

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

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

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

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

【问题讨论】:

  • 没有内置的方法可以做到这一点。您需要手动挑选PATH 元素并在每个元素中搜索notepad.exe
  • system.env("PATH") 也许(我自己也不知道)。
  • 这很脆弱。这取决于您运行它的机器的配置。
  • @duffymo 它很脆弱,但别无选择(除非你掏出where,如阿米拉的回答中所述)。甚至which 命令行实用程序(where 的 Unix 版本)也是以这种方式实现的(即,没有用于执行 execvp 样式查找的库函数)。

标签: java windows environment-variables


【解决方案1】:

没有内置函数可以做到这一点。但是你可以像 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");
}

【讨论】:

  • 感谢 janos 的帮助。
  • 注意,在windows上搜索时,可能还需要搜索File file = new File(dirname, name + ".exe");。如果您希望您的应用程序在所有标准操作系统上运行,您可能需要检查这两种文件。
【解决方案2】:

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

where <executable_name>

例如:

where mspaint 返回:

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

【讨论】:

  • 感谢阿米拉的帮助。
  • 请注意,包含可执行文件的目录必须在 PATH 环境变量中,以便“在哪里”可以找到它。
  • @Ehcnalb, where 适用于 Windows 和 Mac OS X。在 Linux 上,您可以使用 which
猜你喜欢
  • 2010-10-14
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2012-10-20
  • 2011-08-20
  • 1970-01-01
相关资源
最近更新 更多