简体   繁体   中英

xml properties file location in web java app

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM