Reputation: 11
I have a java file inside src/test/java/com/pp/utils. I need to access a properties file example.properties that is inside src/test/resources from this Java file.
I tried it with :
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("example.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("key1"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This gives a FileNotFound Exception. What should be the path? Or where else can I place the properties file so that it gets picked up?
Upvotes: 1
Views: 614
Reputation: 7950
try
InputStream inputStream = getClass().getResourceAsStream("/example.properties");
For clarity this assumes you properties file is in /src/test/resources, that is the root of the classpath, hence the /example.properties.
Upvotes: 2
Reputation: 1567
InputStream addrStream = <current-class>.class.getResourceAsStream("example.properties");
prop .load(addrStream);
if my class name is PropertyUtil
InputStream addrStream = PropertyUtil.class.getResourceAsStream("example.properties");
prop .load(addrStream);
or
InputStream addrStream = getClass().getResourceAsStream("example.properties");
prop .load(addrStream);
use above first code if you are using properties code in main method
.
Upvotes: 0