Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load all files of a folder to a list of Resources in Spring?

Tags:

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

By annotation I could do the following:

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

But how can I achieve the same using spring programmatically?

like image 701
membersound Avatar asked Dec 01 '14 22:12

membersound


People also ask

What does @resource do in spring?

The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection.

How do you load properties file from resources folder in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

How do I put files in a folder in spring boot?

To reliably get a file from the resources in Spring Boot application: Find a way to pass abstract resource, for example, InputStream , URL instead of File. Use framework facilities to get the resource.

What is resource loader in Spring boot?

Spring's resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context. Here's an example to show how to use getResource() to load a text file from. 1.


1 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"); 
like image 107
Maciej Walkowiak Avatar answered Oct 22 '22 08:10

Maciej Walkowiak