Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 查找与模式匹配的所有类路径资源_Java_Spring_Classpath - Fatal编程技术网

Java 查找与模式匹配的所有类路径资源

Java 查找与模式匹配的所有类路径资源,java,spring,classpath,Java,Spring,Classpath,我想通过使用上下文类加载器将文本文件作为资源加载来读取一组文本文件 URL url = Thread.currentThread() .getContextClassLoader() .getResource("folder/foo.txt"); 是否有某种方法可以获取名称与给定模式匹配的资源列表?例如: URL[] matchingUrls = someLibrary.getMatchingResources("folder/*

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

URL url = Thread.currentThread()
                .getContextClassLoader()
                .getResource("folder/foo.txt");
是否有某种方法可以获取名称与给定模式匹配的资源列表?例如:

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

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

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

例如:
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"));
List resources=CPScanner.scanResources(新的PackageNameFilter(“net.sf.corn.cps.*”),新的ResourceNameFilter(“*.xml”);
在pom.xml中使用下面的dependecy

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

玉米网
玉米蛋白
1.0.1
来自“Binil Thomas”的评论是正确的,我希望确认Spring的PathMatchingResourcePatternResolver可以从Java配置中使用,这样我就可以给出生成的“资源”列表添加到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);
工作起来很有魅力。

只需使用:

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

org.springframework.core.io.support.PathMatchingResourcePatternResolver.java似乎是完成这项工作的类。但是,我不能在我的应用程序中使用Spring:(很好。这正是我所需要的。在过去的一年中,我已经需要了四次中的三次,这是迄今为止我遇到的最好的解决方案。OP nixed spring,但这个技巧确实可以很容易地从类路径获取资源模式,并且非常适合我的情况。当我在spring 5中使用List时,我得到了例如,
java.io.FileNotFoundException:无法打开类路径资源[folder/*.xml],因为它不存在
@whitestryder下面的解决方案确实有效。