Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have different XML-files in my 'src/main/recources' folder, and I'd like to read them from my webapplication.

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

The code gets invoked inside a WebService, and this prints out 'C:\Users\Administrator' when I look inside the Tomcat-server-output. My current solution is to put the 'file1.xml'-documents outside of the WAR, in the 'C:\'-folder but this way my WAR is not transferable.

I've also tried

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

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

Regards, Pete

like image 412
JavaPete Avatar asked Jun 04 '10 09:06

JavaPete


People also ask

Which reader reads data from XML file?

This article describes how to use the XmlTextReader class to read the XML data from a file. The XmlTextReader class provides direct parsing and tokenizing of the XML data.

How do I read a resource file?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How do I add a resource file to a jar file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR! EDIT: you can make sure your JAR contains folder by inspecting it using 7zip. Save this answer.


1 Answers

If you are using the standard maven2 war packaging, your file1.xml is copied to the directory WEB-INF/classes within your warfile.

You can access this file via the classpath.

URL resourceUrl = URL.class.getResource("/WEB-INF/classes/file1.xml");
File resourceFile = new File(resourceUrl.toURI());
like image 57
Adriaan Koster Avatar answered Oct 20 '22 03:10

Adriaan Koster