查找与模式匹配的所有CLASSPATH资源

问题描述 投票:12回答:4

我想通过使用上下文类加载器将它们加载为资源来读取一堆文本文件。

URL url = Thread.currentThread()
                .getContextClassLoader()
                .getResource("folder/foo.txt");

是否有某种方法可以获取名称与给定模式匹配的资源列表?例如:

URL[] matchingUrls = someLibrary.getMatchingResources("folder/*.txt");

像Spring这样的库可以扫描类路径以找到具有给定批注的类,因此我想知道是否有类似的东西可以加载一堆资源。

java spring classpath
4个回答
6
投票

Spring支持蚂蚁风格的类路径资源匹配。

http://static.springsource.org/spring/docs/2.5.x/reference/resources.html

示例:classpath:com/mycompany/**/applicationContext.xml, /WEB-INF/*-context.xml

看看您是否可以在项目中使用spring。如果不可能,那么您总是可以拉下源代码以查看它们在做什么,然后自己做:)


13
投票

仅使用:

@Value("classpath:folder/*.xml")
Resource[] resources;

8
投票

来自“ Binil Thomas”的评论走对了,我一直在寻找确认是否可以在Java Config中使用Spring的PathMatchingResourcePatternResolver,以便可以将生成的“ Resource”列表提供给Spring Hibernate SessionFactory.mappingLocations,而无需更新每次添加新的映射文件时,Hibernate * .hbm.xml文件的列表。我可以使用以下代码通过PathMatchingResourcePatternResolver实现此目的:

import org.hibernate.SessionFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
...
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();   
Resource [] mappingLocations = patternResolver.getResources("classpath*:mappings/**/*.hbm.xml");
sessionFactory.setMappingLocations(mappingLocations);

像魅力一样工作。


3
投票

您可以尝试玉米cps

 List<URL> resources = CPScanner.scanResources(new PackageNameFilter("net.sf.corn.cps.*"), new ResourceNameFilter("*.xml"));

在pom.xml中使用以下依赖项

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-cps</artifactId>
    <version>1.0.1</version>
</dependency>
© www.soinside.com 2019 - 2024. All rights reserved.