代码之家  ›  专栏  ›  技术社区  ›  Binil Thomas

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

  •  11
  • Binil Thomas  · 技术社区  · 16 年前

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

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

    有什么方法可以得到名称与给定模式匹配的资源列表吗?例如:

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

    4 回复  |  直到 6 年前
        1
  •  7
  •   Kannan Ekanath    16 年前

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

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

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

        2
  •  13
  •   Igor    10 年前

    只需使用:

    @Value("classpath:folder/*.xml")
    Resource[] resources;
    
        3
  •  11
  •   whitestryder    12 年前

    “比尼尔·托马斯”的评论是对的,我想确认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);
    

    很有魅力。

        4
  •  5
  •   Serhat    13 年前

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

    在pom.xml中使用下面的dependecy

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