Where should I find the xml file if I want to parse it inside a java servlet

I want to parse an XML file inside a servlet, but an exception is raised that the JVM cannot specify the location of the xml file.

here is the exception

java.io.FileNotFoundException: FormFieldsNames.xml (The system cannot find the file specified)

I tried putting the xml file in the direction of the project, java src pachage and inside the servlet patch, but all tese attempts get the same result.

where should i find the xml file, please help and thanks in advance.

+3
source share
3 answers

A common problem with reading files from the classpath is the correct placement in your WAR file.

In Java, a servlet called MyServlet can reference a file like this

InputStream is=MyServlet.getClass().getResourceAsStream("/path/to/file/example.txt")

which will find the file stored in

WEB-INF/classes/path/to/file/example.txt

/ .

(, JNDI). :

InputStream fis = FileInputStream(new File("/usr/share/myapp/another-example.txt"));

, DOM , MyServlet :

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();

.

+4

:

  • WEB-INF/ - getServletContext().getResourceAsStream(..)
  • WEB-INF/classes - , getClass().getResourceAsStream(..)
+2

If you include it in your jar / war file, you can easily load it with Class.getResourceAsStreamor ClassLoader.getResourceAsStream. Do this, not try to download it as an actual file in the file system.

+1
source

Source: https://habr.com/ru/post/1777233/


All Articles