我在类路径上有一个资源集合,大致如下:
com/example/foo
r1.txt
r2.txt
r3.txt
bar/
b1.txt
b2.txt
baz/
x.txt
y.txt
我知道这个包位于 WEB-INF lib 中的类路径上,我希望能够遍历从 com.example.foo 开始的类路径,查找所有 .txt 文件。使用 siganutre 调用类似于以下内容的函数。
列表文件 = findFiles("com/example/foo","*.txt");
我使用的是 spring 3.1,所以我很高兴使用 spring 的任何方法。
UPDATE:使用基于 Spring 的 @jschoen 建议的解决方案如下:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:com/example/foo/**/*.txt");
弹簧使用蚂蚁风格的模式进行匹配,因此需要双**
您可以使用思考库 http://code.google.com/p/reflections/如果我没有记错的话。
public static void main(String[] args) {
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("your.test.more"))
.setScanners(new ResourcesScanner()));
Set<String> textFiles = reflections.getResources(Pattern.compile(".*\\.txt"));
for (String file : textFiles){
System.out.println(file);
}
}
不管你放什么包,你只需要从一个开始,它就会找到所有其他的。
编辑:似乎还有路径匹配资源模式解析器 http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html#getResources%28java.lang.String%29在Spring中你可以使用。它有一个getResources(String locationPattern) http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html#getResources%28java.lang.String%29我假设你可以使用传递模式".*\\.txt"
并且会以同样的方式工作。我所在的地方没有 Spring 设置,否则我会自己测试一下。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)