How can I use ClassLoader.getResources()
to find recursivly resources from my classpath?
E.g.
finding all resources in the META-INF
"directory": Imagine something like
getClass().getClassLoader().getResources("META-INF")
Unfortunately, this does only retrieve an URL
to exactly this "directory".
all resources named bla.xml
(recursivly)
getClass().getClassLoader().getResources("bla.xml")
But this returns an empty Enumeration
.
And as a bonus question: How does ClassLoader.getResources()
differ from ClassLoader.getResource()
?
getResource() method finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.
The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application.
The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.
Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.
The Spring Framework has a class which allows to recursively search through the classpath:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); resolver.getResources("classpath*:some/package/name/**/*.xml");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With