如何将文件夹中的所有文件加载到Spring中的资源列表中?
问题描述:
我有一个文件夹,并希望加载使用Spring和通配符的所有TXT文件到列表:如何将文件夹中的所有文件加载到Spring中的资源列表中?
通过注释,我可以做到以下几点:
@Value("classpath*:../../dir/*.txt")
private Resource[] files;
但我怎么能达到同样使用弹簧编程?
答
使用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
@Autowired
private ApplicationContext applicationContext;
private Resource[] resources ;
public loadResources() {
try {
resources = applicationContext.getResources("file:C:/XYZ/*_vru_*");
} catch (IOException ex) {
ex.printStackTrace();
}
}