我在我的程序中使用这段代码来加载属性文件:
Properties properties = new Properties();
URL url = new App().getClass().getResource(PROPERTIES_FILE);
properties.load(url.openStream());
代码在 Eclipse 中运行良好。然后我将程序打包到一个名为 MyProgram.jar 的 JAR 中,并运行它,我在第二行得到了一个 NullPointerException。 JAR 不包含属性文件,它们都在同一目录中。我正在使用 Maven 创建 JAR。我该如何解决这个问题?
更新:我不想将属性文件添加到 JAR,因为它将在部署时创建。
最佳答案
BalusC 是对的,你需要指示Maven 生成一个MANIFEST.MF
当前目录 ( .
) 在 Class-Path:
中条目。
假设您仍在使用 Maven Assembly 插件和 jar-with-dependencies
构建可执行 JAR 的描述符,您可以使用以下命令告诉插件这样做:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.stackoverflow.App</mainClass>
</manifest>
<manifestEntries>
<Class-Path>.</Class-Path> <!-- HERE IS THE IMPORTANT BIT -->
</manifestEntries>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- append to the packaging phase. -->
<goals>
<goal>single</goal> <!-- goals == mojos -->
</goals>
</execution>
</executions>
</plugin>
关于java - 可执行 jar 找不到属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4126030/