views:

48

answers:

3

Hi,

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

A: 

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) {
  ...
}
John Topley
I do not have a ServletContext object, since this code resides inside a webservice method (Spring-WS). Or am I missing the point?
JavaPete
A: 

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.

techzen
Yes but I want to avoid doing that because a relative path to the file wouldn't require me to have different config files. But I will use this solution if I can't get anything else to work, thanks!
JavaPete
A: 

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());
Adriaan Koster
Ahh it works, I had to modify the first line a bit:URL resourceUrl = Thread.currentThread().getContextClassLoader().getResource("file1.xml");File1.xml has to be in the resources-folder, of course.Thanks a lot!
JavaPete
But why do you need to go via currentThread().getContextClassLoader() ? Is there some sort of security restriction going on in your environment or am I missing something?Are you building your webapp using the standard maven war plugin or via an assembly or otherwise?
Adriaan Koster