How to load a properties file from a servlet
Posted by Saulo on June 28th, 2009 in How-Tos. No Comments

I wanted to read a properties file from a servlet without using a hard-coded, absolute path. I tried to search on the web for a portable solution, but I couldn’t find anything.
Here is the trick: use ServletContext.getRealPath(String). For instance, a file called “config.properties” located in “WEB-INF”, can be loaded like this:
public void init(ServletConfig config) throws ServletException {
String pathToFile = config.getServletContext().getRealPath("")
+ "/WEB-INF/config.properties";
Properties properties = new Properties();
properties.load(new FileInputStream(pathToPropertiesFile));
}
Leave a comment