获取正在运行的JAR文件的路径返回"rsrc:./"

Doe*_*yle 2 java jar rsrc path manifest

我的代码在JAR文件中运行,我需要获取该文件的完整路径.例如,我的JAR名为example.jar,位于D:\ example \所以我需要通过该jar中的一些代码获得"D:\ example\example.jar".我已经尝试了很多方法来获取该路径,但它们都没有正常工作.

其中之一是

getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
Run Code Online (Sandbox Code Playgroud)

很多人说这对他们有用,但对我来说它会返回"rsrc:./".

之后我搜索过,我注意到我的MANIFEST.MF包含这个:

Manifest-Version: 1.0
Rsrc-Class-Path: ./
Class-Path: .
Rsrc-Main-Class: Example
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
Run Code Online (Sandbox Code Playgroud)

我不知道这意味着什么,但如果我删除那些Rsrc的东西并用它替换其他东西,它就说罐子坏了.我认为这就是为什么它不起作用的原因.有谁知道这意味着什么?

PS:我正在使用BAT文件运行我的JAR.

Gre*_*hor 7

我偶然发现了这个问题,并将调查留给了那些在将来问自己rsrc意味着什么的人.

我正在使用Eclipse Mars 1并尝试将我的项目导出为可运行的JAR.在那里我可以选择库处理并决定:

  1. 将所需的库提取到生成的JAR中
  2. 将所需的库打包到生成的JAR中
  3. 将所需的库复制到生成的JAR旁边的子文件夹中

要测试的线是

System.out.println(MyClass.class.getProtectionDomain().getCodeSource().getLocation());
Run Code Online (Sandbox Code Playgroud)

JAR文件的名称是MyJar.jar(将放在桌面上),Project的名称和文件夹是MyProject.

结果:

  1. file:/C:/Users/admin/Desktop/MyJar.jar
  2. rsrc:./
  3. file:/C:/Users/admin/Desktop/MyJar.jar
  4. <表示在Eclipse中运行> file:/C:/Development/workspace/MyProject/target/classes/

我为此写了一个方便的方法:

public class SystemUtils {

    /**
     * Let no one instanciate this class.
     */
    private SystemUtils() {}

    /**
     * If the current JVM was started from within a JAR file. 
     * @return <code>Boolean.TRUE</code> if it is, <code>Boolean.FALSE</code> if it is not, <code>null</code> if unknown.
     */
    public static Boolean executedFromWithinJar() {
        Boolean withinJar = null;
        try {
            String location = SystemUtils.class.getProtectionDomain().getCodeSource().getLocation().toString();
            if (location.startsWith("rsrc:")
                || location.endsWith(".jar") && !new File(location.substring(location.indexOf(':') + 1)).isDirectory())
                withinJar = Boolean.TRUE;
            else
                withinJar = Boolean.FALSE;
        }
        catch (Exception ex) {/* value is still null */}
        return withinJar;
    }

}
Run Code Online (Sandbox Code Playgroud)