Java 如何在类路径上遍历目录树以查找资源文件?
我在类路径上收集了一些资源,大致如下:Java 如何在类路径上遍历目录树以查找资源文件?,java,spring,Java,Spring,我在类路径上收集了一些资源,大致如下: com/example/foo r1.txt r2.txt r3.txt bar/ b1.txt b2.txt baz/ x.txt y.txt 我知道这个包位于WEB-INF库中的类路径上,我希望能够遍历从com.example.foo开始的类路径,查找所有的.txt文件。使用类似于下面的siganutre调用函数 List files=findFiles(
com/example/foo
r1.txt
r2.txt
r3.txt
bar/
b1.txt
b2.txt
baz/
x.txt
y.txt
我知道这个包位于WEB-INF库中的类路径上,我希望能够遍历从com.example.foo开始的类路径,查找所有的.txt文件。使用类似于下面的siganutre调用函数
List files=findFiles(“com/example/foo”,“*.txt”)
我正在使用Spring3.1,所以我很乐意使用spring中的任何方法
更新:
使用基于Spring的@jschoen建议的解决方案如下:
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:com/example/foo/**/*.txt");
弹簧使用蚂蚁式图案匹配,因此需要双**如果我没有弄错的话,您可以使用
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);
}
}
publicstaticvoidmain(字符串[]args){
反射反射=新反射(新配置生成器()
.setURL(ClasspathHelper.forPackage(“your.test.more”))
.setScanners(新资源扫描程序());
设置textFiles=reflections.getResources(Pattern.compile(.\\.txt));
用于(字符串文件:文本文件){
System.out.println(文件);
}
}
不管你放什么包,你只需要一个开始,它就会找到所有其他的
编辑:在春天,你也可以使用它。我假设您可以使用pass模式“*\\\.txt”
,并以同样的方式工作。我现在没有Spring设置,否则我会自己测试