How to read a properties file in java web application
How to read a properties file in java web application
The best method for a programmer to load a property file inside a Java web application is to read the property file location and call it using
<context -param> <param -name/>serverpropertiesfile <param -value/>/WEB-INF/classes/server.properties </context>
The above xml is taken from my WEB.XML file.
The advantage of this approach is that you don’t have to provide the filename/path every time you call the property file. It is really handy when the class files are located in different location.
Here you can declare the param-name as something that can be used as a reference to the original file name.
Let the content or data inside the server.properties file be
DATA=This is a test property that will load the value of DATA from the properties file.
Param-value will have the relative path of the property file.
Here in the above example i am giving the param-name as serverpropertiesfile and the param-value as /WEB-INF/classes/server.properties
Now how to read this property file from a Java code?
It is very simple all you have to do is
String path_prop = getServletContext().getInitParameter("serverpropertiesfile"); final InputStream is = getServletContext().getResourceAsStream(path_prop); // load a properties file prop.load(is); // get the property value and print it out String path = prop.getProperty("DATA"); System.out.println(path);