where should i locate xml file if i want to parse it inside java servlet
I want to parse xml file 开发者_C百科inside servlet, but an exception happen which JVM cannot specify the xml file location.
here's the exception
java.io.FileNotFoundException: FormFieldsNames.xml (The system cannot find the file specified)
i tried to put the xml file in the project direction, java src package, and inside the package of servlets but all of these tries get the same result.
where should i locate xml file , please help and thanks in advance.
A common problem with reading files from the classpath is getting the location correct in your WAR file.
In Java, a servlet called MyServlet could reference the file like this
InputStream is=MyServlet.getClass().getResourceAsStream("/path/to/file/example.txt")
which will locate a file stored under
WEB-INF/classes/path/to/file/example.txt
Note the leading / which often catches people out.
It is possible for the application container to read from the local file system (say if you wanted to get hold of external properties and didn't want to use JNDI). For that you'd use the usual file access process:
InputStream fis = FileInputStream(new File("/usr/share/myapp/another-example.txt"));
Of course, if you want to point DOM at it then MyServlet could contain the following:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
InputStream is = MyServlet.getClass().getResourceAsStream("/path/to/my/example.xml");
Document document = documentBuilder.parse(new InputSource(is));
// And start exploring the NodeList...
NodeList nodeList = document.getFirstChild().getChildNodes();
That should do the trick.
The usual locations are:
WEB-INF/
- obtained bygetServletContext().getResourceAsStream(..)
WEB-INF/classes
- obtained by either the above, orgetClass().getResourceAsStream(..)
If you include it in your jar/war file, you should be able to load it easily with Class.getResourceAsStream
or ClassLoader.getResourceAsStream
. Do that rather than trying to load it as an actual file on the file system.
精彩评论