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 ?

- 1,812
- 13
- 17
-
*"I don't know the file names."* Why not? Who put them in there? How did they put them in there (e.g. Ant, Maven etc)? – Andrew Thompson Jul 17 '12 at 07:21
-
@ Andrew: As part of the build process, these files are generated and are packaged in the jar file by ANT. – NiranjanBhat Jul 17 '12 at 09:50
-
Generate a list using Ant and include it in a known location in one of the Jars. Read the list at run-time. – Andrew Thompson Jul 17 '12 at 10:21
-
That is what I am doing now :) – NiranjanBhat Jul 17 '12 at 15:40
1 Answers
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)

- 343,457
- 22
- 230
- 366
-
-
@mhrsalehi From memory, yes, they can, but they might inherit the parent class loaders class path as well – MadProgrammer Mar 20 '20 at 11:37