How can I discover resources in a Java jar with a wildcard name?

前端 未结 5 539
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 02:55

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

相关标签:
5条回答
  • 2021-01-18 03:22

    Well, it is not from within Java, but

    jar -tvf jarname | grep xml$

    will show you all the XMLs in the jar.

    0 讨论(0)
  • 2021-01-18 03:31

    A Spring ApplicationContext can do this trivially:

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

    See ResourcePatternResolver#getResources, or ApplicationContext.

    0 讨论(0)
  • 2021-01-18 03:34

    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.

    0 讨论(0)
  • 2021-01-18 03:34
     List<URL> resources = CPScanner.scanResources(new PackageNameFilter("net.sf.corn.cps.sample"), new ResourceNameFilter("A*.xml"));
    

    put the snippet in your pom.xml

    <dependency>
        <groupId>net.sf.corn</groupId>
        <artifactId>corn-cps</artifactId>
        <version>1.0.1</version>
    </dependency>
    
    0 讨论(0)
  • 2021-01-18 03:37

    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.

    0 讨论(0)
提交回复
热议问题