How to Access Resource Files in Packaged Spring + Maven Project (WAR/JAR)

Maven is quite clear about both expected resource directory structure and the resulting directory in which they’ll appear after deployment:

“The default resource directory for all Maven projects is src/main/resources which will end up in target/classes and in WEB-INF/classes in the WAR. The directory structure will be preserved in the process.”

What’s not so clear, however, is that these resources are in fact added to the root classpath relative to the WAR/JAR. What’s still less clear is the proper way of accessing these dynamic resources – both for testing and in source code – as the directory path changes upon deployment. If your resources are external references, the task is trivial with the help of Java’s getClass().getResources(), which returns an URL. Unfortunately, if your resource file name contains spaces, the resulting url will include “%20” characters in their stead. You could parse this resulting string and replace infringing characters, but why re-invent the wheel?  Spring provides a fantastic utility – ResourceUtils – that allows for a more elegant solution:

 

private static final String MY_RESOURCE_FILENAME = "test.txt";

File myResourceAsFile = ResourceUtils.getFile(getClass().getResource(MY_RESOURCE_FILENAME));

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s