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));