我的代码在 JAR 文件内运行,我需要获取该文件的完整路径。 例如,我的 JAR 名为 example.jar,位于 D:\example\ 所以我需要通过该 jar 内的一些代码获取“D:\example\example.jar”。 我尝试了很多方法来获取该路径,但没有一个能正常工作。
其中之一是
getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
很多人说这对他们有用,但对我来说它返回“rsrc:./”。
之后我进行了搜索,我注意到我的 MANIFEST.MF 包含以下内容:
Manifest-Version: 1.0
Rsrc-Class-Path: ./
Class-Path: .
Rsrc-Main-Class: Example
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
我不知道这意味着什么,但如果我删除 Rsrc 的东西并用它替换其他东西,它会说 jar 坏了。我认为这就是它不起作用的原因。有谁知道这是什么意思吗?
PS:我正在使用 BAT 文件运行 JAR。
最佳答案
我也偶然发现了这个问题,并将我的调查留在这里,供将来问自己 rsrc
含义的人使用。
我正在使用 Eclipse Mars 1 并尝试将我的项目导出为可运行的 JAR。在那里我可以选择库处理并在以下之间做出决定:
- 将所需的库提取到生成的 JAR 中
- 将所需的库打包到生成的 JAR 中
- 将所需的库复制到生成的 JAR 旁边的子文件夹中
要测试的线路是
System.out.println(MyClass.class.getProtectionDomain().getCodeSource().getLocation());
JAR 文件的名称是 MyJar.jar(将放在桌面上),项目的名称和文件夹是 MyProject。
结果:
文件:/C:/Users/admin/Desktop/MyJar.jar
rsrc:./
文件:/C:/Users/admin/Desktop/MyJar.jar
- <表示在 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;
}
}
关于java - 获取正在运行的 JAR 文件的路径返回 "rsrc:./",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37902711/