繁体   English   中英

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

[英]Finding all CLASSPATH resources matching a pattern

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

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

有没有办法获取名称与给定模式匹配的资源列表? 例如:

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

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

只需使用:

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

“Binil Thomas”的评论在正确的轨道上,我正在寻找可以从 Java Config 中使用 Spring 的 PathMatchingResourcePatternResolver 的确认,以便我可以将生成的“资源”列表提供给 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);

奇迹般有效。

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

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

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

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

你可以试试corn-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>

暂无
暂无

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

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