How to switch from ResourceBundle to Properties (class)?
I have an app split into 2 Java projects (core & web). A Java service in the core module have to read values from a .properties file located in the web module. When I use ResourceBundle, it works as expected.
I wanted to switch to the Properties class for several reasons (esp. because the ResourceBundle is cached and I don't want to implement the ResourceBundle.Control to have no cache). Unfortunately I can't get it to work, particularly because I can't find out which correct relative path to use.
I read the decompiled ResourceBundle class (et al.) and noticed the use of getResource() on some ClassLoader. So instead of directly using FileInputStream, I tested with getResource() or simply getResourceAsStream() on ServiceImpl.class or ResourceBundle.class but still no success...
Anyone having an idea how to get this work? Thanks!
This is my app core with the service getting the property values:
app-core
src/main/java
com.my.company.impl.ServiceImpl
public void someRun() {
String myProperty = null;
myProperty = getPropertyRB("foo.bar.key"); // I get what I want
myProperty = getPropertyP("foo.bar.key"); // not here...
}
private String getPropertyRB(String key) {
ResourceBundle bundle = ResourceBundle.getBundle("properties/app-info");
String property = null;
try {
property = bundle.getString(key);
} catch (MissingResourceException mre) {
// ...
}
return property;
}
private String getPropertyP(String key) {
Properties properties = new Properties();
InputStream inputStream = new FileInputStream("properties/app-info.properties"); // Seems like the path isn't the good one
properties.load(inputStream);
// ... didn't include all the try/catch stuff
return properties.getProperty(key);
}
This is the web module where resides the properties file:
app-web
src/main/resources
/properties
app-info.properties
You should use getResource()
or getResourceAsStream()
with proper path and classloader.
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("properties/app-info.properties");
Make sure the file is named app-info.properties
, and not something like app-info_en.properties
which would be found by ResourceBundle
(when the context matches) but not by getResourceAsStream()
.