Store xml files in a resource folder (WAR), read from code

I have different XML files in my src / main / recources folder and I would like to read them from my web application.

File f = new File("file1.xml");
f.getAbsolutePath();

This code is called inside the WebService, and it outputs "C: \ Users \ Administrator" when I look at the output of the Tomcat server. My real solution is to put the documents "file1.xml" outside of the WAR, in the folder "C: \", but in this way my WAR cannot be transferred.

I also tried

    <bean name="webService">
        <property name="document">
         <value>classpath:file1.xml</value>
        </property>
    </bean>

But it just prints "classpath: file.xml" without parsing it.

Regards, Pete

+5
source share
3 answers

maven2, file1.xml WEB-INF/classes .

.

URL resourceUrl = URL.class.getResource("/WEB-INF/classes/file1.xml");
File resourceFile = new File(resourceUrl.toURI());
+5

WEB-INF ( WEB-INF), ServletContext getResourceAsStream:

try {
  InputStream is = context.getResourceAsStream("/WEB-INF/file1.xml");
  ...
} catch (IOException e) {
  ...
}
0

You can put the path information in the properties file, which is located in the / WEB -INF / classes path, and load this information into the application at run time.

To have a different value for this path property, you can use the profile option of maven or any other build tool — so that another environment causes the WAR file to have the correct property value for the path suitable for that environment.

0
source

All Articles