如何在类路径上查找资源文件的目录树?

时间:2012-10-30 17:40:48

标签: java spring

我在类路径上有一些资源集合:

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调用函数。

List files = findFiles(“com / example / foo”,“*。txt”);

我正在使用spring 3.1,所以我很乐意使用春天的任何方法。

更新 使用基于Spring的@jschoen建议的解决方案如下:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:com/example/foo/**/*.txt");

弹簧匹配使用蚂蚁风格图案,因此需要双**

1 个答案:

答案 0 :(得分:2)

如果我没弄错的话,你可以使用Reflections library

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);
    }
}

你放的是什么包没关系,你只需要一个开始,它会找到所有其他包。

编辑:在Spring中似乎也可以使用PathMatchingResourcePatternResolver。它有getResources(String locationPattern),我认为你可以使用传递模式".*\\.txt"并以相同的方式工作。我没有Spring设置,或者我自己会测试它。

相关问题