tags:

views:

1175

answers:

5

I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern. Is there any way to do this?

A: 

Well, it's not from within java, but

jar -tvf jarname | grep xml$

will show you all the xmls in the jar.

Steve B.
Unfortuneately I need a solution that is within Java.
+2  A: 

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.

sblundy
This looks like it would work but would involve a fair amount of searching to get to the file names I want. I'm thinking that it will be easier to create a file at buid time that contains the files I'm looking at. This new file would have a known name and could be found using the ClassLoader.
+1  A: 

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.

corlettk
A: 

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."
}
jchilders
A: 

A Spring ApplicationContext can do this trivially:

 ApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml");
 Resource[] xmlResources = context.getResources("classpath:/**/*.xml");

See ResourcePatternResolver#getResources, or ApplicationContext.

flicken