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

牧云@^-^@ 提交于 2019-12-06 20:14:46

问题


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?


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



回答2:


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


来源:https://stackoverflow.com/questions/27238746/how-to-load-all-files-of-a-folder-to-a-list-of-resources-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!