Yashica
Yashica

Reputation: 45

Reading Config.Properties file from src/test/resources folder in MAVEN project

I am new to Maven and building a project with maven and try to load config.properties file from src/test/resources folder. I tried searching solution to my problem but no success as of now. Can someone please help me in this ?

my project structure is like this :

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

pom.xml includes

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

 </build>

code to fetch config file :

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);
                    } 
     }

}

Tried many options, but still getting File Not Found Exception: property file 'config.properties' not found in the class path NOTE: if i am using config.properties file from src/main/resources (default location of maven). it is working fine

Please help me. Thanks in advance !!

Upvotes: 2

Views: 7650

Answers (1)

glytching
glytching

Reputation: 47865

Assuming that this file is correctly copied to the runtime classpath then it can be addressed as follows:

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

But ...

  1. A 'test' resource will not be on the non-test runtime classpath and it's not clear whether the code you posted is run within a 'test context' or not.
  2. You seem to be trying to load this file from InputStream inputStream = loader.getResourceAsStream("config.properties") rather than from InputStream inputStream = loader.getResourceAsStream("Configuration/config.properties")

Upvotes: 1

Related Questions