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" withou开发者_如何学Ct parsing it.
Regards, Pete
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());
If you put the file in a directory underneath WEB-INF (or within WEB-INF itself) then you can read it using the ServletContext
's getResourceAsStream
method:
try {
InputStream is = context.getResourceAsStream("/WEB-INF/file1.xml");
...
} catch (IOException e) {
...
}
You can put the path info in the properties file that is in the path /WEB-INF/classes - and load this info in the application at runtime.
To have different value for this path property you can use the option of maven profiles or any other build tool - so that different environment results in the WAR file having the right properties value for the path suited for that environment.
精彩评论