简体   繁体   中英

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

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?

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");

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();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM