java 如何在 Spring 中将文件夹的所有文件加载到资源列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27238746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load all files of a folder to a list of Resources in Spring?
提问by membersound
I have a folder and want to load all txt files to a list using Spring and wildcards:
我有一个文件夹,想使用 Spring 和通配符将所有 txt 文件加载到列表中:
By annotation I could do the following:
通过注释,我可以执行以下操作:
@Value("classpath*:../../dir/*.txt")
private Resource[] files;
But how can I achieve the same using spring programmatically?
但是如何以编程方式使用 spring 来实现相同的目标?
回答by Maciej Walkowiak
Use ResourceLoaderand ResourcePatternUtils:
使用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);
}
}
and use it like:
并像这样使用它:
Resource[] resources = foobar.loadResources("classpath*:../../dir/*.txt");
回答by Baji Shaik
If you are using Spring
如果您使用的是 Spring
@Autowired
private ApplicationContext applicationContext;
public void loadResources() {
try {
Resource[] resources = applicationContext.getResources("file:C:/XYZ/*_vru_*");
} catch (IOException ex) {
ex.printStackTrace();
}
}