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

时间:2014-12-01 22:43:39

标签: java spring spring-batch

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

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

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

但是如何以编程方式使用spring实现相同的目标呢?

3 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:4)

如果您使用的是Spring

@Autowired
private ApplicationContext applicationContext;
private Resource[] resources ;

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

答案 2 :(得分:0)

applicationContext.getResources("classpath:/*.extension");对我有用