How to use ClassLoader.getResources() correctly?

JavaResourcesClasspathClassloaderGetresource

Java Problem Overview


How can I use ClassLoader.getResources() to find recursivly resources from my classpath?

E.g.

  • finding all resources in the META-INF "directory": Imagine something like

    getClass().getClassLoader().getResources("META-INF")

Unfortunately, this does only retrieve an URL to exactly this "directory".

  • all resources named bla.xml (recursivly)

    getClass().getClassLoader().getResources("bla.xml")

But this returns an empty Enumeration.

And as a bonus question: How does ClassLoader.getResources() differ from ClassLoader.getResource()?

Java Solutions


Solution 1 - Java

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

Solution 2 - Java

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Solution 3 - Java

This is the simplest wat to get the File object to which a certain URL object is pointing at:

File file=new File(url.toURI());

Now, for your concrete questions:

> * finding all resources in the META-INF "directory":

You can indeed get the File object pointing to this URL

Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
	URL metaInf=en.nextElement();
	File fileMetaInf=new File(metaInf.toURI());
	
    File[] files=fileMetaInf.listFiles();
	//or 
	String[] filenames=fileMetaInf.list();
}

> * all resources named bla.xml > (recursivly)

In this case, you'll have to do some custom code. Here is a dummy example:

final List<File> foundFiles=new ArrayList<File>();

FileFilter customFilter=new FileFilter() {
	@Override
	public boolean accept(File pathname) {
				
		if(pathname.isDirectory()) {
			pathname.listFiles(this);
		}
		if(pathname.getName().endsWith("bla.xml")) {
			foundFiles.add(pathname);
			return true;
		}
		return false;
	}
			
};		
//rootFolder here represents a File Object pointing the root forlder of your search	
rootFolder.listFiles(customFilter);

When the code is run, you'll get all the found ocurrences at the foundFiles List.

Solution 4 - Java

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }

Solution 5 - Java

MRalwasser, I'd give you a hint, cast the URL.getConnection() to JarURLConnection. Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.

The rest I leave to you.

Hope this helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMRalwasserView Question on Stackoverflow
Solution 1 - JavarecView Answer on Stackoverflow
Solution 2 - JavakrockView Answer on Stackoverflow
Solution 3 - JavaTomas NarrosView Answer on Stackoverflow
Solution 4 - JavaMark ButlerView Answer on Stackoverflow
Solution 5 - JavabestsssView Answer on Stackoverflow