6
我有一個文件夾,並希望加載使用Spring和通配符的所有TXT文件到列表:如何將文件夾中的所有文件加載到Spring中的資源列表中?
通過註釋,我可以做到以下幾點:
@Value("classpath*:../../dir/*.txt")
private Resource[] files;
但我怎麼能達到同樣使用彈簧編程?
我有一個文件夾,並希望加載使用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();
}
}