【问题标题】:Loading properties file gives null加载属性文件给出 null
【发布时间】:2013-08-08 11:59:51
【问题描述】:

main() 类中我放了一个代码:

App.getClass().getClassLoader().getResourceAsStream("Repo-Offer.properties")

结果是null

属性文件位于:

Project/src/main/resources/properties/Repo-Offer.properties 

我试图加载这样的属性:

private Properties getPropertiesFromClasspath(String propFileName) throws IOException {
    // loading xmlProfileGen.properties from the classpath
    Properties props = new Properties();
    InputStream inputStream = this.getClass().getClassLoader()
        .getResourceAsStream(propFileName);

    if (inputStream == null) {
        throw new FileNotFoundException("property file '" + propFileName
            + "' not found in the classpath");
    }

    props.load(inputStream);

    return props;
}

但因为它说的是 null

  Exception in thread "main" java.io.FileNotFoundException: Repo-Offer.properties

如何使用来自以下位置的属性文件: 项目/src/main/resources/properties/Repo-Offer.properties 而源在

Project/src/main/java/com/...

编辑 它是 Maven 项目。

【问题讨论】:

  • 尝试加载getResourceAsStream("properties/Repo-Offer.properties")。有用吗?
  • 这真的是一个Maven项目吗?您是如何创建和运行最终工件的?
  • @Dave Newton 是的,它是 maven 项目。从 Eclipse GUI 界面运行它。
  • @LaurentG 在下面看到我的答案

标签: java properties classpath filenotfoundexception


【解决方案1】:

假设您使用的是 Maven,属性文件将位于 /properties/Repo-Offer.properties,因此将其用作文件路径。 查看target/classes 以验证正确的路径。

【讨论】:

  • 对于:System.out.println(App.getClass().getClassLoader().getResourceAsStream("/properties/Repo-Offer.properties") 我不断收到:null
  • @mCs 没有领先的/ 怎么办?
  • @Dave Newton 是的,就是这样。谢谢领导/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
相关资源
最近更新 更多