1

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?

Lars Celie
  • 592
  • 4
  • 15

2 Answers2

3

If the file is in the classpath, you can get it as input stream with something like this:

InputStream in = this.getClass().getResourceAsStream("xml/db/oracle-properties.xml");
Cristian Sevescu
  • 1,094
  • 6
  • 11
  • This gives me a nullpointerexception, and the files are located in the WEB-INF folder. – Lars Celie Jan 21 '15 at 13:09
  • WEB-INF content is not part of classpath, except WEB-INF/classes. Have a look [here](http://stackoverflow.com/questions/4340653/file-path-to-resource-in-our-war-web-inf-folder) – Cristian Sevescu Jan 21 '15 at 13:26
1

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);
Community
  • 1
  • 1
Lars Celie
  • 592
  • 4
  • 15