Finding all CLASSPATH resources matching a pattern

本小妞迷上赌 提交于 2019-12-20 12:59:54

问题


I want to read a bunch of text files, by loading them as resources using the context classloader.

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

Is there some way to get a list of resources whose names match a given pattern? For eg:

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

Libraries like Spring can scan the classpath to find classes with a given annotation, so I am wondering if there something similar to load a bunch of resources.


回答1:


Spring supports ant-style class path resource matching.

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

Examples like : classpath:com/mycompany/**/applicationContext.xml, /WEB-INF/*-context.xml

See if you can use spring for your project. If it is not possible then you can always pull down the source code to see what they are doing, and do that yourself :)




回答2:


Just use:

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



回答3:


Comment from "Binil Thomas" was on the right track, I was looking for confirmation that Spring's PathMatchingResourcePatternResolver could be used from Java Config so that I could give the resulting "Resource" list to the Spring Hibernate SessionFactory.mappingLocations without having to update the list of Hibernate *.hbm.xml files every time a new mapping file was added. I was able to achieve this with the PathMatchingResourcePatternResolver using the below code:

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

Works like a charm.




回答4:


You can try corn-cps

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

Use the dependecy below in your pom.xml

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-cps</artifactId>
    <version>1.0.1</version>
</dependency>


来源:https://stackoverflow.com/questions/2766933/finding-all-classpath-resources-matching-a-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!