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?
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.
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().
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With