简体   繁体   中英

Getting the path to current dynamic web project JAVA

How can I access an XML file while my application is already deployed?

I'm running a Dynamic Web Application with several classes and a simple rest service, but I don't have any actual servlets, so accessing the ServletContext is not possible, (as far as I know) so using getRealPath() won't work.

An example: I have a class DBcon which connects to a database, but has to load the properties from an XML file, which are located at /xml/db/oracle-properties.xml

In a normal Java project you can simply use a file input stream, but it won't work for a dynamic web application.

How can I still load the xml file?

如果文件在类路径中,则可以使用类似以下内容的文件作为输入流:

InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");

I figured out by reading this: Where to place and how to read configuration resource files in servlet based application?

I've put the xml files in WEB-INF/classes and then used this code to load it:

InputStream xmlFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    prop.loadFromXML(xmlFile);

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