I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern. Is there any way to do this?
Well, it's not from within java, but
jar -tvf jarname | grep xml$
will show you all the xmls in the jar.
It requires a little trickery, but here's an relevant blog entry. You first figure out the URLs of the jars, then open the jar and scan its contents. I think you would discover the URLs of all jars by looking for `/META-INF/MANIFEST.MF'. Directories would be another matter.
A JAR-file is just another ZIP-file, right?
So I suppose you could iterate the jar-files using http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html
I'm thinking something like:
ZipSearcher searcher = new ZipSearcher(new ZipInputStream(new FileInputStream("my.jar")));
List xmlFilenames = searcher.search(new RegexFilenameFilter(".xml$"));
Cheers. Keith.
I have to do this so often that I just wrote a bash function for it. Put this in your .bashrc and go:
# Find a file (technically any string) within a jar listing
function ffjar() {
MATCHES=0
jars=`find . -type f -iname '*.jar' -print`
for jar in ${jars}
do
jarContents=`unzip -l ${jar}`
for line in ${jarContents}
do
if [[ ${line} == *$1* ]]
then
echo "${jar}: [${line}]"
MATCHES=$((MATCHES + 1))
fi
done
done
echo "$MATCHES matches."
}
A Spring ApplicationContext
can do this trivially:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml");
Resource[] xmlResources = context.getResources("classpath:/**/*.xml");
See ResourcePatternResolver#getResources, or ApplicationContext.