【问题标题】:How to scan the search path for executables如何扫描可执行文件的搜索路径
【发布时间】:2015-12-11 10:24:08
【问题描述】:

在Java中是否可以通过shell命令获取文件的路径?

例如,当我在 Windows 命令提示符下键入 php -v 时,它会知道我指的是 C:\php\php.exe(对于我自己的计算机),因为我将它添加到系统 Path 变量中。是否可以在 Java 中做同样的事情?

我知道你可以从Java中获取Path环境变量并使用String.split(";")进行解析,但不知道有没有更直接的方法?

【问题讨论】:

  • 我不建议这样做,但您可以在 Linux 上调用本机命令,如 which 或在 Windows 上调用 where.exe。恕我直言,解析 PATH 变量是一个更简洁的选择。
  • 也许通过使用 jmx ? bean 可能会暴露这一点,但这只是一个想法。扫描路径不是一个好主意,因为尽管路径上有一个 php,但可以直接调用另一个 php。
  • 这个问题已经回答了hereherehere。我可能错过了一些。您可能想查看 this answer 以获得仅限 Windows 的解决方案
  • @pgmann 我说的是系统$PATH 环境变量,而不是java home。所以,基本上我想在不调用命令的情况下以编程方式获得像@Amaud 所述的输出(where/which)。不过我之前不知道那个命令。

标签: java cmd path


【解决方案1】:

看看下面来自 JGit 库的代码 http://download.eclipse.org/jgit/site/3.7.1.201504261725-r/apidocs/org/eclipse/jgit/util/FS.html#searchPath(java.lang.String,%20java.lang.String...)

你可以实现类似的东西

/**
 * Searches the given path to see if it contains one of the given files.
 * Returns the first it finds. Returns null if not found or if path is null.
 *
 * @param path
 *            List of paths to search separated by File.pathSeparator
 * @param lookFor
 *            Files to search for in the given path
 * @return the first match found, or null
 * @since 3.0
 **/
protected static File searchPath(final String path, final String... lookFor) {
    if (path == null)
        return null;

    for (final String p : path.split(File.pathSeparator)) {
        for (String command : lookFor) {
            final File e = new File(p, command);
            if (e.isFile())
                return e.getAbsoluteFile();
        }
    }
    return null;
}

【讨论】:

    【解决方案2】:

    您也许可以使用来自my Java Command Prompt 的这段摘录做一些事情。

    String cmd = "which "+<insert executable to find>; // linux
    String cmd = "where "+<insert executable to find>; // windows
    
    Process p = Runtime.getRuntime().exec(cmd);
    
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    while ((s = stdInput.readLine()) != null) {
        ref.log.setText(ref.log.getText()+s+"\n");
        ref.updateDisplay();
    }
    // read any errors from the attempted command
    while ((s = stdError.readLine()) != null) {
        ref.log.setText(ref.log.getText()+s+"\n");
        ref.updateDisplay();
    }
    

    输出应该包含文件的路径。

    【讨论】:

    • 看来java.lang.Runtime.exec 也要求命令是绝对路径?
    • @Pemapmodder 我不这么认为...我稍后再检查。
    • @Pemapmodder 根据这篇文章,它继承了Java进程的路径:stackoverflow.com/a/1319314/1476989
    • 哦,谢谢,我可能把它和 Process 搞混了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2017-05-25
    • 2011-09-30
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多