Search code examples
javaclassloader

Using the ClassLoader method to retrieve all resources under classes as Input Streams


My problem is one that you would think is quite common, but I haven't so far managed to find a solution.

Building a Java web app under Tomcat 5.5 (although a requirement is that it can be deployed anywhere, like under a WebLogic environment, hence the loading resources as streams requirement). Good practice dictates that resource files are placed under WEB-INF/classes and loaded using the ClassLoader's getResourceAsStream() method. All well and good when you know the name of the resource you want to load.

My problem is that I need to load everything (including recursively in non-empty sub-directories) that lives in a subdirectory of classes.

So, for example, if I have the following under WEB-INF/classes:

folderX/folderY

folderX/folderY/fileA.properties

folderX/fileB.properties

I need the fileA.properties and fileB.properties classes to be loaded, without actually knowing their names before the application is started (ie I need the ability to arbitrarily load resources from any directory under WEB-INF/classes).

What is the most elegant way to do this? What object could I interrogate to find the information I need (the resource paths to each of the required resources)? A non-servlet specific solution would be best (keeping it all within the class loading framework if possible).

Thanks in advance!


Solution

  • You can do that with some tricks :)

    Get the resource as URL, extract the protocol :

    • file protocol - get the URL path and you have a folder, scan for files.
    • jar/zip protocol - extract the jar/zip path and use JarFile to browse the files and extract everything under your path/package.