25

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?

3 Answers 3

47

Use ResourceLoader and 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);
    }
}

and use it like:

Resource[] resources = foobar.loadResources("classpath*:../../dir/*.txt");
9

If you are using Spring

@Autowired
private ApplicationContext applicationContext;

public void loadResources() {
    try {
        Resource[] resources = applicationContext.getResources("file:C:/XYZ/*_vru_*");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
0

applicationContext.getResources("classpath:/*.extension"); works for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.