【问题标题】:Unable to access/run executable jar placed within the project无法访问/运行放置在项目中的可执行 jar
【发布时间】:2015-01-23 08:03:44
【问题描述】:

我正在尝试在我的项目的resources 文件夹中运行一个可执行的 jar。如果我将 jar 放在文件系统的任何目录中并提供绝对路径,它就可以正常工作。 请看下面的代码:

    String jarPath = "C:\\JarFolder\\myJar.jar";        
    String command = "java -jar";
    String space = " ";
    String params = "-a abc";
    try {
        proc = Runtime
                .getRuntime()
                .exec(command + space + jarPath + space + params);
    } catch (IOException e) {
        e.printStackTrace();
    }

但是当我将 jar 放在 resources 文件夹中,并将相对 jar 路径设置为:

    String jarPath = "..\\..\\..\\resources\\myJar.jar";

我收到一个错误:Error: Unable to access jarfile ..\\..\\..\\resources\\myJar.jar

我已经验证了路径,它是有效的。 我在这里做错了吗?这是正确的方法吗?

【问题讨论】:

  • 调用时会得到什么:Runtime .getRuntime() .exec("cmd /c dir ..\\..\\..\\resources");我> ?
  • 您在 Windows 虚拟文件夹之一中吗?用户的Documents 或类似名称。它们可能会导致命令行出现问题
  • >> 驱动器 D 中的卷是新卷 >> 卷序列号是 92A4-BDF7 >> >> D:\Software\eclipse 目录 >> >>找不到文件`
  • 你可以尝试用命令行访问它吗?
  • 由于(来自@agad 提出的 cmd 测试)您似乎正在搜索文件夹 D:\Software\eclipse,请仔细检查您是否有文件夹 D:\Software\eclipse\resources 并且它包含正确的非空文件 @ 987654329@

标签: java jar executable-jar


【解决方案1】:

使用 ClassLoader 获取资源的路径。

String jarPath = this.getClass().getClassLoader().getResource("myJar.jar").getPath();      
String command = "java -jar";
String space = " ";
String params = "-a abc";
try {
    proc = Runtime
            .getRuntime()
            .exec(command + space + jarPath + space + params);
} catch (IOException e) {
    e.printStackTrace();
}

如果这是从主静态方法运行的,那么只需将 this.getClass() 替换为 YourClass.class。

【讨论】:

    【解决方案2】:

    相对路径应该可以直接使用。需要您看到的错误描述和项目文件夹结构的更多详细信息(执行 jar 放置在哪里以及导入文件夹放置在哪里。)

    其他替代解决方案是查找当前正在执行的 jar 文件的绝对文件位置。您可以使用以下代码 sn-p 获取它。

    MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
    

    其他要执行的jar文件必须放在同一个文件夹的某处或某些子文件夹中。

    现在从绝对路径中删除当前的jar文件名并附加另一个jar文件的相对路径并执行它。它应该可以工作。

    【讨论】:

      【解决方案3】:

      如果你在窗口,你可以使用如下。我已经测试了这段代码,它可以工作。

      public class test {
          public static void main(String[]args) throws IOException{
              String jarPath = test.class.getClass().getResource("/resources/b.jar").getPath();      
              System.out.println("jarPath "+ jarPath);
      //the result path have extra "/" so we have to remove it as follow.
              jarPath = jarPath.substring(1);
      //and again the result is encoded so we need to decode it back
              jarPath = URLDecoder.decode(jarPath);
              Runtime
              .getRuntime()
              .exec("java -jar \""+jarPath+"\"");
          }
      
      }
      

      注意:我将可运行的 jar 放在名为“b.jar”的资源文件夹中。

      上面的代码需要一些修改以满足您的需求。 祝你好运

      【讨论】:

        猜你喜欢
        • 2011-10-20
        • 1970-01-01
        • 2015-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-01
        • 2018-05-19
        • 2013-05-18
        相关资源
        最近更新 更多