tags:

views:

591

answers:

3

How do I locate resources on the classpath in java? Specifically stuff that ends in .hbm.xml.

My goal is to get a List of all resources on the classpath that end with ".hbm.xml".

+3  A: 

You have to get a classloader, and test whether it's a URLClassLoader. If so, downcast and get its URLs. From there, open each as a JarFile and look at its entries. Apply a regex to each entry and see if it's one that interests you.

Clearly, this isn't fast. It's best to be given a name to be looked up in the classpath, perhaps listed in a standard file name in the META-INF directory of each classpath element, similar to the technique used by the ServiceProvider facility. Note that you can list all files with a given name on the classpath.

erickson
A: 

MyClass.class.getClassLoader().getResourceAsStream("Person.hbm.xml") is one way to look for it.

anjanb
can someone say why they gave a NEGATIVE scoring ? That way, I can improve next time. thank you.
anjanb
Maybe because the OP asks for a method of retrieving a list of resources. Your code is related, but is only useful AFTER that list has been created and a file is chosen to be loaded in.
Cheekysoft
A: 

My problem is a variation on the original post. I know exactly where the resources I am looking for are located. They are an indeterminate number of XML files in a specific directory (and its subdirectories), in the same Jar that my code is running in. I'm wondering if there's a quicker/more efficient way to navigate directly to that parent directory and then discover any XML files in that directory or any child directories. Just to be clear, the number and names of the XML files are not known - all that is known is that they are under this parent subdirectory.