Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a XML file in a maven project so it stays available when packaged

Tags:

java

maven-2

I currently started working on a maven web-app project that needs to be launched with the jetty:run-exploded goal for development/debugging in eclipse.

Now, I have an XML file which contents I need to access at runtime. My problem is: where to put the file so that the code that does the reading works both in "exploded" and packaged (i.e. in the WAR) mode?

Putting the file in src/main/java (so as to be in the classpath) won't cut it since maven filters out all non-java files on packaging. When the file is in src/main/resources, one mean would be to figure out the root path of the project (during eclipse development) and look into that directory - but this won't be the case anymore when the project will be packaged.

Of course I could go into writing code that tries to read the file from both locations, but this seems rather cumbersome. Any suggestions?

like image 719
Manuel Bernhardt Avatar asked Apr 15 '10 06:04

Manuel Bernhardt


1 Answers

Files in src/main/resources are copied to the target/classes directory and are available on the class path. Just read them from the class path. As explained in How do I add resources to my JAR? from the maven documentation (with a test resource here):

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...
like image 186
Pascal Thivent Avatar answered Oct 05 '22 02:10

Pascal Thivent