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()
?
This question is related to
java
resources
classpath
classloader
getresource
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);
}
}
}
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");
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!
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.
Source: Stackoverflow.com