How to load all files of a folder to a list of Resources in Spring?(如何在Spring中将文件夹的所有文件加载到资源列表中?)
问题描述
我有一个文件夹,希望使用Spring和通配符将所有txt文件加载到列表中:
通过注释,我可以执行以下操作:
@Value("classpath*:../../dir/*.txt")
private Resource[] files;
但是我如何使用Spring以编程方式实现相同的功能?
推荐答案
使用ResourceLoader和ResourcePatternUtils:
class Foobar {
private ResourceLoader resourceLoader;
@Autowired
public Foobar(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
Resource[] loadResources(String pattern) throws IOException {
return ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(pattern);
}
}
并按如下方式使用:
Resource[] resources = foobar.loadResources("classpath*:../../dir/*.txt");
这篇关于如何在Spring中将文件夹的所有文件加载到资源列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!