views:

44

answers:

1

Hi, I have a web app in java, and in a servlet I need to load properties from a xml file.

The code is

XMLReader reader = XMLReaderFactory.createXMLReader();
...       
FileInputStream fis = new FileInputStream("myconf.xml");
reader.parse(new InputSource(fis));

My question is: where should the myconf.xml file be placed in the war file so the servlet can find it?

Thanks

+4  A: 

Don't use FileInputStream with a relative path. You would be dependent on the current working directory over which you have totally no control from inside the Java code. Rather put the file in the classpath and use ClassLoader#getResourceAsStream().

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("/myconf.xml");

This example expects the file to be in the root of the classpath. From IDE perspective, this can be the root of the src folder or the root of the /WEB-INF/classes folder. You can even put it somewhere else externally and add its (absolute!) path to the runtime classpath somewhere in the server config.

See also:

BalusC
Also pay attention to the way that the ClassLoader is obtained here. This is the correct way to do it. The incorrect way, which I see way too often, is something like this: this.getClass().getClassLoader().
Mike Baranczak
It's indeed the preferred way in case of (web)applications where multiple hierarchial classloaders plays a role. You should not rely on the classloader of the class you're currently sitting in. In "simple" (desktop) applications with a single classloader it doesn't harm.
BalusC