[英]How to load all files of a folder to a list of Resources in Spring?
我有一個文件夾,想使用 Spring 和通配符將所有 txt 文件加載到列表中:
通過注釋,我可以執行以下操作:
@Value("classpath*:../../dir/*.txt")
private Resource[] files;
但是我怎樣才能以編程方式使用spring來實現同樣的效果呢?
使用ResourceLoader和ResourcePatternUtils :
class Foobar {
private final ResourceLoader resourceLoader;
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;
public void loadResources() {
try {
Resource[] resources = applicationContext.getResources("file:C:/XYZ/*_vru_*");
} catch (IOException ex) {
ex.printStackTrace();
}
}
applicationContext.getResources("classpath:/*.extension"); 為我工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.