Read Classpath Resource from Jar Files with Spring

Share on:

To read resources from classpath, you can use the Spring class ClassPathResource. The constructor with one argument reads only resources from file system.  But sometimes you want to read a resources from a jar file in the classpath.  For this case, you must build an own URLClassLoader from the URL of the jar file and use the ClassPathResource constructor with the arguments path and classLoader.  The path value is the path of the resource in the jar file.

An Example

We have a jar file, named example.jar. The content looks as follows:

1example.jar
2  |_ META-INF
3     |_ sample-resource.txt

We want to read the sample-resource.txt.  The source code for this example looks as follows:

1URL jarUrl = new File("path_to_jar_file").toURI().toURL();
2URLClassLoader jarLoader = new URLClassLoader(new URL[]{jarUrl}, Thread.currentThread().getContextClassLoader());
3ClassPathResource sampleResource = new ClassPathResource("META-INF/sample-resource.txt",jarLoader);