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:
example.jar |_ META-INF |_ sample-resource.txt
We want to read the sample-resource.txt. The source code for this example looks as follows:
URL jarUrl = new File("path_to_jar_file").toURI().toURL(); URLClassLoader jarLoader = new URLClassLoader(new URL[]{jarUrl}, Thread.currentThread().getContextClassLoader()); ClassPathResource sampleResource = new ClassPathResource("META-INF/sample-resource.txt",jarLoader);
Advertisements