How to find all resources in the classpath with the specified name?

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

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

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

PS: I don’t have the luxury of using any third-party libraries, so you need a solution for the home.

+4
source share
2 answers

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

For instance:

 Enumeration<URL> enumer = Thread.currentThread().getContextClassLoader().getResources("/Path/To/xyz.properties"); while (enumer.hasMoreElements()) { System.out.print(enumer.nextElement()); } 
+4
source

What I do, I read the java source files from the class path and process them using ClassLoader . I am using the following 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.

+1
source

Source: https://habr.com/ru/post/1438661/


All Articles