Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locate all resources in classpath with a specified name?

Tags:

java

I want to list all files with a specific name in the class path. I am expecting multiple occurrences, hence Class.getResource(String) will not work.

Basically I have to identify all files with a specific name (ex: xyz.properties) anywhere in the class path and then read the metadata in them cumulatively.

I want something of the effect Collection<URL> Class.getResources(String) but could not find anything similar.

PS: I don't have the luxury of using any third party libraries, hence in need of a home grown solution.

like image 998
Shama Avatar asked Oct 09 '12 13:10

Shama


2 Answers

You can use Enumeration getResources(String name) on the class loader to achieve the same.

For example:

Enumeration<URL> enumer = Thread.currentThread().getContextClassLoader().getResources("/Path/To/xyz.properties");
while (enumer.hasMoreElements()) {
    System.out.print(enumer.nextElement());
}
like image 77
Ashwin Prabhu Avatar answered Nov 01 '22 13:11

Ashwin Prabhu


What I do is I read java source files from classpath and process them using ClassLoader. I am using follwing code :

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

assert (classLoader != null);

// pkgName = "com.comp.pkg"
String path = pkgName.replace('.', '/');

// resources will contain all java files and sub-packages
Enumeration<URL> resources = classLoader.getResources(path);

 if(resources.hasMoreElements()) {
        URL resource = resources.nextElement();     
        File directory = new File(resource.getFile());
        // .. process file, check this directory for properties files
 }

Hope this helps you.

like image 38
Nandkumar Tekale Avatar answered Nov 01 '22 12:11

Nandkumar Tekale