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: wh开发者_StackOverflow社区ere 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:
getResourceAsStream()
vsFileInputStream
精彩评论