如何在带有通配符名称的 Java jar 中发现资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/133229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I discover resources in a Java jar with a wildcard name?
提问by
I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern. Is there any way to do this?
我想使用通配符模式发现我的 ClassLoader 知道的所有 xml 文件。有没有办法做到这一点?
采纳答案by sblundy
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.
它需要一些技巧,但这里有一个相关的博客条目。您首先找出 jar 的 URL,然后打开 jar 并扫描其内容。我认为您会通过查找`/META-INF/MANIFEST.MF' 来发现所有 jar 的 URL。目录将是另一回事。
回答by flicken
A Spring ApplicationContextcan do this trivially:
SpringApplicationContext可以很简单地做到这一点:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationConext.xml");
Resource[] xmlResources = context.getResources("classpath:/**/*.xml");
See ResourcePatternResolver#getResources, or ApplicationContext.
回答by Serhat
List<URL> resources = CPScanner.scanResources(new PackageNameFilter("net.sf.corn.cps.sample"), new ResourceNameFilter("A*.xml"));
put the snippet in your pom.xml
把代码片段放在你的 pom.xml 中
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-cps</artifactId>
<version>1.0.1</version>
</dependency>
回答by corlettk
A JAR-file is just another ZIP-file, right?
JAR 文件只是另一个 ZIP 文件,对吗?
So I suppose you could iterate the jar-files using http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html
所以我想你可以使用http://java.sun.com/javase/6/docs/api/java/util/zip/ZipInputStream.html迭代 jar 文件
I'm thinking something like:
我在想这样的事情:
ZipSearcher searcher = new ZipSearcher(new ZipInputStream(new FileInputStream("my.jar")));
List xmlFilenames = searcher.search(new RegexFilenameFilter(".xml$"));
ZipSearcher searcher = new ZipSearcher(new ZipInputStream(new FileInputStream("my.jar")));
List xmlFilenames = searcher.search(new RegexFilenameFilter(".xml$"));
Cheers. Keith.
干杯。基思。
回答by Steve B.
Well, it is not from within Java, but
嗯,它不是来自 Java 内部,而是
jar -tvf jarname | grep xml$
jar -tvf jarname | grep xml$
will show you all the XMLs in the jar.
将向您展示 jar 中的所有 XML。

