How to use ClassLoader.getResources() in jar file

classloader, jar, java

Solution

For what you are trying to do I don't think it is possible.

`getResource` and `getResources` are about finding named resources within the classloader's classpath, not listing values beneath a directory or folder.

So for example `ClassLoader.getResources("mycompany/configuration/file/Config.cfg")` would return all the files named Config.cfg that existed in the mycompany/configuration/file path within the class loader's class path (I find this especially useful for loading version information personally).

In your case I think you might almost have half a solution. The URL you are getting back contains the source jar file (jar:file:/C:/myJarName.jar). You could use this information to crack open the jar file a read a listing of the entries, filtering those entries whose name starts with "mycompany/configuration/file/".

From there, you could then fall back on the `getResource` method to load a reference to each one (now that you have the name and path)

Problem

Problem statement: I have a jar file with a set of configuration files in a package `mycompany/configuration/file/`. I don't know the file names. My intention is to load the file names at runtime from the jar file in which they are packaged and then use it in my application. As far as I understood: When I use the `ClassLoader.getResources("mycompany/configuration/file/")` I should be getting all the configuration files as URLs. However, this is what is happening: I get one URL object with URL like `jar:file:/C:/myJarName.jar!mycompany/configuration/file/` Could you please let me know what I am doing wrong ?

Original source