如何使用通配符名称发现Java jar中的资源?

我想发现我的ClassLoader使用通配符模式知道的所有xml文件。 有没有办法做到这一点?

它需要一些小技巧,但这是一个相关的博客条目 。 首先找出jar子的URL,然后打开jar子并扫描其内容。 我想你会通过查找`/META-INF/MANIFEST.MF’来发现所有jar子的URL。 目录将是另一回事。

Spring ApplicationContext可以做到这一点:

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

请参阅ResourcePatternResolver#getResources或ApplicationContext 。

  List resources = CPScanner.scanResources(new PackageNameFilter("net.sf.corn.cps.sample"), new ResourceNameFilter("A*.xml")); 

把代码段放在你的pom.xml中

  net.sf.corn corn-cps 1.0.1  

JAR文件只是另一个ZIP文件,对吧?

所以我想你可以使用http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html来迭代jar文件

我想的是:

ZipSearcher searcher = new ZipSearcher(new ZipInputStream(new FileInputStream("my.jar"))); List xmlFilenames = searcher.search(new RegexFilenameFilter(".xml$"));

干杯。 基思。

好吧,它不是来自Java内部,而是

jar -tvf jarname | grep xml$

将显示jar中的所有XML。