Reputation: 2997
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...
Upvotes: 2
Views: 5245
Reputation: 42060
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.
Upvotes: 1
Reputation: 61178
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!");
}
Upvotes: 3