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



Question:

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:1

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.


Solution:2

As far as I am aware, there is no such ability, since the classloader only attempts to load things it is asked for. It doesn't pre-fetch all items on the classpath, or treat them as a directory structure.

The way I would solve the problem is create a directory listing in a text file of all relevant resources at build time and include that in the war, and then walk it through that way.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »