How to upload all folder files to a resource list in Spring?

I have a folder and you want to load all txt files into a list using Spring and wildcards:

In the annotation, I could do the following:

@Value("classpath*:../../dir/*.txt") private Resource[] files; 

But how can I achieve the same using Spring programmatically?

+11
source share
2 answers

Use ResourceLoader and 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"); 
+21
source

If you use spring

 @Autowired private ApplicationContext applicationContext; public void loadResources() { try { Resource[] resources = applicationContext.getResources("file:C:/XYZ/*_vru_*"); } catch (IOException ex) { ex.printStackTrace(); } } 
+5
source

Source: https://habr.com/ru/post/978966/


All Articles