0

I want to load a few parameters from a xml file on my Tomcat server. let´s say thats the folder structure:

 Tomcat
 |-webapps
   |-MyWebApp.war
   |-MyWebApp //(Source files)
      |-META-INF
      |-WEB-INF
         |-configFile.xml  

I tried several different methods like

File inputfile = new File("/MyWebApp/WEB-INF/configFile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputfile);

which just delivered a filemissing exception...

So the question is:

HOW do I have to set the path in my Java code to refer to files on my Tomcat ?

wero
  • 32,544
  • 3
  • 59
  • 84
JohnDizzle
  • 1,268
  • 3
  • 24
  • 51

2 Answers2

1

You should avoid to use files in a web application.

Here is the way to go: You need to obtain a ServletContext (e.g. being inside a Servlet).

Then use

ServletContext context = ...
InputStream in = context.getResourceAsStream("/WEB-INF/configFile.xml");

to open an InputStream to your XML file and pass it to the DocumentBuilder.

Document doc = dBuilder.parse(in);
wero
  • 32,544
  • 3
  • 59
  • 84
  • How can I get the ServletContext ? I just have a simple REST service class which calls my (service)class to open the file and get the prams. – JohnDizzle Feb 04 '16 at 10:36
  • @JohnDizzle inject the context into your service class, e.g. for JAX-RS see http://stackoverflow.com/questions/1814517/get-servletcontext-on-tomcat-from-jax-rs-jersey – wero Feb 04 '16 at 10:40
-1

Try this

File inputfile = new File("/WEB-INF/configFile.xml");

OR

File inputfile = new File("../WEB-INF/configFile.xml");
Piyush Ghediya
  • 1,754
  • 1
  • 14
  • 17