How to read a properties file outside my webapp context in Tomcat
41,527
Solution 1
There are multiple approaches .
- Use an Environmental variable
- Use a System Property
- Set it as a Application Context Param in Web.xml
Heres a sample ,that showsOption 1 and Option 2
try {
//Use Any Environmental Variable , here i have used CATALINA_HOME
String propertyHome = System.getenv("CATALINA_HOME");
if(null == propertyHome){
//This is a system property that is passed
// using the -D option in the Tomcat startup script
propertyHome = System.getProperty("PROPERTY_HOME");
}
String filePath= propertyHome+"/properties/myapp.properties";
Properties property = new Properties();
property.load(SystemTest.class.getClassLoader().getResourceAsStream(filePath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Solution 2
I prefer the option to configure via Tomcat context descriptors.
These XML-documents are placed into the folder tomcat/conf/Catalina/<host>/*.xml
This refers to: Externalizing Tomcat webapp config from .war file
Solution 3
In our project that we config the path of file as vm arguments which will stored in the tomcat properties and in the code, use System.getProperty(the parameter you config)
to get the path and read the properties file, then get the results.
Author by
Fernando
Updated on October 04, 2020Comments
-
Fernando over 3 years
I have this requirement that my webapp needs to read from a properties file outside the Tomcat webapps directory, for example from $CATALINA_HOME/properties/myapp.properties. I have tried several things but so far no luck
-
Fernando about 11 yearsThank you! I used your second approach with System Property "catalina.home" This is exactly what I needed!
-
Andrew Niken about 9 yearsYeah, but in case Tomcat and if I need read file somewhere in class .... implements ServletContextListener {} I got WAR related path ! Is it possible something using for example SPRING to get path outside of WAR ? file:d:/my/path/toFile.log