How to use ClassLoader.getResources() correctly? [duplicate] How to use ClassLoader.getResources() correctly? [duplicate] java java

How to use ClassLoader.getResources() correctly? [duplicate]


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");


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.


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.