2

I can't load correctly a file xml from my servlet: that's the code:

       try{

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.parse("db.xml");
       } catch (Exception ex) {
       ex.printStackTrace();
           out.print("File Not Found!");
   }

the db.xml is inside the classes folder with the class and the java file...

Usi Usi
  • 2,967
  • 5
  • 38
  • 69

2 Answers2

3

You need to use getResourceAsStream()

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(getClass().getResourceAsStream("db.xml"));
    } catch (Exception ex) {
        ex.printStackTrace();
        out.print("File Not Found!");
    }
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
1

If you have the XML file in the root folder of the war file, you can read it using the real path for the context application folder.

String contextPath = request.getSession().getServletContext().getRealPath("/");

In another way, you can use the context class loader in a multi-module environment:

ClassLoader classloader = Thread.currentThread().getContextClassLoader()
Document doc = db.parse(classloader.getResourceAsStream(contextPath+ "/db.xml"));

In some environments, the additional slash is not necessary.

Community
  • 1
  • 1
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148