繁体   English   中英

如何将文件夹的所有文件加载到 Spring 中的资源列表中?

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

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

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

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

但是我怎样才能以编程方式使用spring来实现同样的效果呢?

使用ResourceLoaderResourcePatternUtils

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

并像这样使用它:

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

如果您使用的是 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"); 为我工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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