【问题标题】:Access property file from within JAR Maven project从 JAR Maven 项目中访问属性文件
【发布时间】:2017-11-18 01:21:07
【问题描述】:

在阅读了大约 50 个关于该主题的不同主题后,我无法找到任何解决方案。

我要做的是访问 jar 中的 config.properties 文件。

我的项目是一个Maven项目,架构如下:

  • 我的项目
    • src/main/java
      • 我的应用程序
        • MyClass.java
    • src/main/资源
      • icon.jpg
      • config.properties

因此,当我尝试从 Eclipse 访问它时,它可以很好地使用此代码:

InputStream configFile = MyClass.class.getResourceAsStream("config.properties"); Followed by more code here to retrieve properties...(that works)

但是,当我将项目导出到可运行的 JAR 时,它不再起作用。 jar里面的文件如下:

  • 文件.jar
    • 我的应用程序
      • files.class 在这里
      • 等等……
    • 元信息
    • 资源
      • icon.jpg
      • config.properties

【问题讨论】:

  • <resources> 部分发布到您的pom.xml 文件中
  • 您的构建 jar 文件中真的有 resources 文件夹吗?如果是,我假设您的配置/目录布局或您的 pom 配置错误...
  • 这是我的 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>myapp</groupId> <artifactId>myapp</artifactId> <version>0.0.1-SNAPSHOT</version> <name>myapp</name> <properties> <sonar.host.url>http://localhost:9000</sonar.host.url> </properties> </project>
  • 这看起来像是在使用 Eclipse 来导出 jar。不要那样做。配置 maven 以便它创建正确的 jar 清单并改用 maven 构建的输出。
  • 我已经完成了 Run as > Maven 安装,但是我得到的 JAR 文件没有运行。而且我的 pom.xml 中仍然没有

标签: java eclipse maven jar properties


【解决方案1】:

尝试以下方法:

InputStream input = AnyClass.class.getResourceAsStream("/config.properties");

它应该可以工作。

【讨论】:

    【解决方案2】:

    试试这个:

    InputStream configFile = MyClass.class.getResourceAsStream("resources/config.properties");
    

    【讨论】:

    • JAR 不起作用。我在 Eclipse 中得到一个 NullPointerException。
    • 试试前面的斜线:InputStream configFile = MyClass.class.getResourceAsStream("/resources/config.properties");
    • 还是不行。我想我已经尝试了所有的可能性,但它就是行不通。
    • 尝试Thread.currentThread().getContextClassLoader() 而不是MyClass.class。尝试使用和不使用斜线...
    • 我以前做过。它在 Eclipse 中有效,但在生成 jar 时无效。
    猜你喜欢
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 2011-11-18
    • 2018-09-28
    相关资源
    最近更新 更多