如何在Spring中将文件夹的所有文件加载到资源列表中? [英] How to load all files of a folder to a list of Resources in Spring?

查看:27
本文介绍了如何在Spring中将文件夹的所有文件加载到资源列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,希望使用Spring和通配符将所有txt文件加载到列表中:

通过注释,我可以执行以下操作:

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

但是我如何使用Spring以编程方式实现相同的功能?

推荐答案

使用ResourceLoaderResourcePatternUtils

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

并按如下方式使用:

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

这篇关于如何在Spring中将文件夹的所有文件加载到资源列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆