gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:31:41 24 4
gpt4 key购买 nike

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

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

列出文件 = findFiles("com/example/foo","*.txt");

我使用的是 spring 3.1,所以我很乐意使用 spring 中的任何方法。

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

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

spring 匹配使用 ant 样式模式因此需要双 **

最佳答案

您可以使用 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);
}
}

不管你放什么包,你只需要一个开始,它会找到所有其他的。

编辑:似乎还有 PathMatchingResourcePatternResolver在 Spring 中,你可以使用。它有一个 getResources(String locationPattern)我假设您可以使用传递模式 ".*\\.txt" 并以相同的方式工作。我所在的地方没有 Spring 设置,否则我会自己测试一下。

关于java - 如何在查找资源文件的类路径上遍历目录树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com