How to load a properties file from a servlet

config.properties

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

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>