【发布时间】:2011-04-07 08:18:00
【问题描述】:
问题说明了一切。
在我的情况下,特殊之处在于当前工作目录不是 jar 文件的位置,而是c:\Windows\system32(我的 jar 文件是由 windows 使用右键菜单启动的,我想将文件夹的路径传递为jar 的参数)。
现在我想加载一个名为 config.xml 的配置文件,它与 jar 位于同一文件夹中。当然,该文件的目的是为 jar 提供设置。对我来说重要的是 xml 文件位于 jar 文件的外部以便于编辑。
我很难加载该文件。 Windows 执行该行
cmd /k java -jar D:\pathToJarfile\unpacker-0.0.1-SNAPSHOT-jar-with-dependencies.jar
使用 cmd /k 调用整个过程会打开 Windows 命令提示符,以便我可以看到 jar 的输出。
我不能使用new File(".") 或System.getProperty("user.dir") 作为相对路径,因为这些函数分别返回C:\Windows\system32\. 和C:\Windows\system32(这是Windows 执行AFAIK 的所有内容的工作文件夹)。
Launcher.class.getResourceAsStream("/../config.xml") 也没有成功。由于该路径以/ 开头,因此搜索从 jar 的根节点开始。转到../config.xml 正好指向该文件,但调用返回null。
有人能指出我正确的方向吗?我真的被困在这里了。这个文件加载的东西真的每次都让我很烦......
我自己的要求:
- 我不想在 java 源代码中硬编码路径
- 我不想将文件路径作为参数传递给
java -jar调用(既不作为main(String[] args)的参数,也不使用-Dpath=d:\...设置系统属性)
除了原来的问题,我在使用jar-with-dependencies时很难让maven2将Class-Path: .放入MANIFEST.MF(BalusC发布的解决方案)。
问题是该行出现在常规 jar 的 MANIFEST 文件中,而不是 jar-with-dependencies.jar 的 MANIFEST 文件中(生成了 2 个 jar 文件)。
对于任何关心我是如何做到的人:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
<configuration>
<archive>
<manifest>
<mainClass>${mainClass}</mainClass>
<addClasspath>true</addClasspath>
<!--at first, i tried to place the Class-Path entry
right here using <manifestEntries>. see below -->
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<goals>
<goal>attached</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>${mainClass}</mainClass>
</manifest>
<!--this is the correct placement -->
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
</execution>
</executions>
</plugin>
【问题讨论】: