开发者

Finding all CLASSPATH resources matching a pattern

开发者 https://www.devze.com 2022-12-28 22:22 出处:网络
I want to read a bunch of text files, by loading them as resources using the context classloader. URL url = Thread.currentThread()

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

URL url = Thread.currentThread()
                .getContextClassLoader()
         开发者_JS百科       .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.


Just use:

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


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.


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消