How to load a properties file using JUnit / Ant?

I am using Ant 1.8, JUnit 4.8.2. I am trying to load a properties file and have some problems. The properties file is located in the root directory of my source directory, and I load it into the class path, as well as explicitly loading the properties file into the class path. Below is my Ant build.xml file. This is how I try to load properties ...

private void loadTestProperties() { try { Properties prop = new Properties(); InputStream in = getClass().getResourceAsStream("db.properties"); prop.load(in); in.close(); } catch (Exception e) { fail("Failed to load properties: " + e.getMessage()); } // try } // loadTestProperties 

It always fails with zero (properties were not loaded).

 <project name="leads-testing" default="build" basedir="."> <property name="tst-dir" location="/Users/davea/Documents/workspace-sts-2.6.0.SR1/infinitiusa_leads_testing/test" /> <property name="db-props-file" location="/Users/davea/Documents/workspace-sts-2.6.0.SR1/infinitiusa_leads_testing/test/db.properties" /> <property name="TALK" value="true" /> <path id="classpath.base"> </path> <path id="classpath.test"> <pathelement location="lib/junit-4.8.2.jar" /> <pathelement location="lib/selenium-java-client-driver.jar" /> <pathelement location="lib/classes12.jar" /> <pathelement location="${tst-dir}" /> <pathelement location="${db-props-file}" /> <path refid="classpath.base" /> </path> <target name="compile-test"> <javac srcdir="${tst-dir}" verbose="${TALK}" > <classpath refid="classpath.test"/> </javac> </target> <target name="clean-compile-test"> <delete verbose="${TALK}"> <fileset dir="${tst-dir}" includes="**/*.class" /> </delete> </target> <target name="test" depends="compile-test"> <junit> <classpath refid="classpath.test" /> <formatter type="brief" usefile="false" /> <test name="com.criticalmass.infinitiusa.tests.InfinitiConfigOldG25Base" /> </junit> </target> <target name="all" depends="test" /> <target name="clean" depends="clean-compile-test" /> </project> 

Does anyone know the correct way to load a properties file? Thanks - Dave

+4
source share
2 answers

Attempting to load a resource from getClass().getResourceAsStream() will lead to a search for db.properties based on the package name for the class, that is, in the directory (in the classpath), for example com/criticalmass/infinitiusa/...

Instead, to load from the root of the class path, try something like

 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); 
+5
source
 InputStream in = getClass().getResourceAsStream("db.properties"); 

Try "/db.properties" . See Class.getResourceAsStream ()

For Ant, file paths are allowed relative to the working directory. Therefore, if you are working with the project root, the file will be in src/${db-props-file} .

+1
source

All Articles