palAlaa
palAlaa

Reputation: 9858

where should i locate xml file if i want to parse it inside java servlet

I want to parse xml file 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.

Upvotes: 2

Views: 3530

Answers (3)

Gary
Gary

Reputation: 7257

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.

Upvotes: 4

Bozho
Bozho

Reputation: 597144

The usual locations are:

  • WEB-INF/ - obtained by getServletContext().getResourceAsStream(..)
  • WEB-INF/classes- obtained by either the above, or getClass().getResourceAsStream(..)

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501163

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.

Upvotes: 1

Related Questions