在Get location of JAR file据说“只要你的类路径只包含一个条目,这就可以[获取可运行的 jar 文件的位置]”。
这是我的代码:
public static void main(String[] args) {
System.out.println(System.getProperty("java.class.path"));
}
我创建了一个可运行的 jar(使用 Eclipse Export),当我运行它时,无论我将 CLASSPATH 设置为什么,我只得到可运行的 jar 的路径。
例如:
C:\TEMP>set CLASSPATH=C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>echo %CLASSPATH%
C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>set CLASSPATH
CLASSPATH=C:\TEMP\BackupCompilations\Photos;C:\FreeOCR\tessdata
C:\TEMP>java -jar C:\Programs\bin\Test_one_prop.jar
C:\Programs\bin\Test_one_prop.jar
我还尝试在命令行上使用 -cp。
有人能想出一个反例吗?它返回的东西比我正在运行的 jar 文件的位置更多/不是?
(了解在 Eclipse 中它返回我项目的 bin 文件夹。)
这是我唯一关心的用例:将此程序作为可运行的 jar 运行。
谢谢。
最佳答案
-jar
[...]
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.
当使用 -jar
选项时,.jar
本身用作整个类路径。
Can some one come up with a counter-example where this returns something more/other than the location of the jar file I'm running?
正常情况下,不会。但是,它只是一个属性,因此您可以更改它的值。
System.setProperty("java.class.path", "garbage");
正如 nramaker 在他们的 answer 中建议的那样,您可以通过 MANIFEST 文件提供要包含在类中的其他 jar 的位置。 Java 教程解释了如何执行此操作:
但是,这不会更改 java.class.path
属性的值。如果要从 list 文件中提取 Class-Path
属性的值,可以使用以下提供的解决方案:
一个例子,
URLClassLoader cl = (URLClassLoader) Example.class.getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
System.out.println(manifest.getMainAttributes().getValue(new Attributes.Name("Class-Path")));
} catch (IOException e) {
// handle
}
关于java - 为什么 java.class.path 属性总是返回 jar 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979136/