【问题标题】:Reading Config.Properties file from src/test/resources folder in MAVEN project从 MAVEN 项目的 src/test/resources 文件夹中读取 Config.Properties 文件
【发布时间】:2018-05-13 11:43:45
【问题描述】:

我是 Maven 新手,使用 maven 构建项目并尝试从 src/test/resources 文件夹加载 config.properties 文件。我尝试寻找解决问题的方法,但到目前为止还没有成功。有人可以帮我吗?

我的项目结构是这样的:

ProjectName
--- src/test/java
       --- utilities
           ----utilities.java
                 ---getProperty()
----src/test/resources
        ----Configuration
              ---config.properties

pom.xml 包含

<build>
   <resources>
     <resource>
       <directory>src/test/resources</directory>
       <filtering>true</filtering>
     </resource>
   </resources>

 </build>

获取配置文件的代码:

public class utilities()
     {
        public void getProperty()
     {
     Properties prp=new Properties();
     String propFilePath = "src/test/resources/Configuration/config.properties";
     String[] tmpArray = propFilePath.split("/");
     String propFileName=tmpArray[tmpArray.length - 1];
     ClassLoader loader = Thread.currentThread().getContextClassLoader();
     InputStream inputStream = loader.getResourceAsStream(propFileName);

                if (inputStream != null)
                    {
                        prp.load(inputStream);
                    } 
     }

}

尝试了许多选项,但仍然得到 File Not Found Exception: property file 'config.properties' not found in the class path 注意: 如果我使用 src/main/resources 中的 config.properties 文件(maven 的默认位置)。它工作正常

请帮助我。提前致谢!!

【问题讨论】:

  • 您能否确认记录的位置以确保相对路径有效?
  • 是的,没错
  • 请编辑帖子以展示您如何证明这一点。

标签: maven configuration


【解决方案1】:

假设这个文件被正确复制到运行时类路径,那么它可以被如下寻址:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = loader.getResourceAsStream("Configuration/config.properties");

但是……

  1. “测试”资源不会位于非测试运行时类路径中,并且不清楚您发布的代码是否在“测试上下文”中运行。
  2. 似乎试图从InputStream inputStream = loader.getResourceAsStream("config.properties")而不是InputStream inputStream = loader.getResourceAsStream("Configuration/config.properties")加载此文件

【讨论】:

  • 您好 Glytching,感谢您的回复。我必须对代码进行哪些更改?这样我就可以工作了。我的框架需要配置文件存在于 src/test/resources/Configuration/Config.properties 文件夹中,并且我的输入流始终为空。
  • 我也试过用这个 InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);还是没有机会
  • propFileName 的正确值是“Configuration/config.properties”而不是“config.properties”。当然,这个文件必须在你的运行时类路径中。
  • 你能解释一下运行时 clasapath 吗?
  • “运行时类路径”是运行你的类的 JVM 使用的类路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-26
  • 1970-01-01
  • 2015-02-26
相关资源
最近更新 更多