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

感情迁移 提交于 2019-12-01 16:19:44

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 Spring ApplicationContext can do this trivially:

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

See ResourcePatternResolver#getResources, or ApplicationContext.

 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>

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.

Steve B.

Well, it is not from within Java, but

jar -tvf jarname | grep xml$

will show you all the XMLs in the jar.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!