可执行 jar 找不到属性文件 [英] Executable jar won't find the properties files

查看:24
本文介绍了可执行 jar 找不到属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中使用此代码加载属性文件:

I use this code in my program to load a properties file:

Properties properties = new Properties();
URL url = new App().getClass().getResource(PROPERTIES_FILE);
properties.load(url.openStream());

代码在 Eclipse 中运行良好.然后我将程序打包到一个名为 MyProgram.jar 的 JAR 中,并运行它,我在第二行得到一个 NullPointerException.JAR 不包含属性文件,它们都在同一目录中.我正在使用 Maven 创建 JAR.我该如何解决这个问题?

The code runs fine in Eclipse. Then I package the program into a JAR named MyProgram.jar, and run it, I got a NullPointerException at the second line. The JAR doesn't contain the properties file, they both are in the same directory. I am using Maven to create the JAR. How can I fix this problem?

更新:我不想将属性文件添加到 JAR,因为它将在部署时创建.

UPDATE: I don't want to add the properties file to the JAR, since it will be created at deployment time.

推荐答案

BalusC 是对的,需要指示 Maven 生成一个 MANIFEST.MF 与当前目录(.)code>) 在 Class-Path: 条目中.

BalusC is right, you need to instruct Maven to generate a MANIFEST.MF with the current directory (.) in the Class-Path: entry.

假设您仍在使用 Maven 程序集插件和 jar-with-dependencies 描述符来构建您的可执行 JAR,您可以使用以下命令告诉插件这样做:

Assuming you're still using the Maven Assembly Plugin and the jar-with-dependencies descriptor to build your executable JAR, you can tell the plugin to do so using the following:

  <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>

这篇关于可执行 jar 找不到属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆