Java Resource、Resources、InputStream获取

1、基于Spring(Resource)

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource resource = patternResolver.getResource("/com/superz/yaml/res_1.yaml");
System.out.println(resource.getURL());

// 获取InputStream
resource.getInputStream();

2、基于Spring(Resources)

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
// 路径规则:AntPathMatcher,?匹配一个字符、*匹配0个或多个字符、**匹配0个或多个目录
Resource[] resources = patternResolver.getResources("classpath:/**/res*.yaml");
for (Resource _res : resources) {
    System.out.println(_res.getURL());
    // 获取InputStream
    resource.getInputStream();
}

3、基于reflections(Resources)


   org.reflections
   reflections
   0.9.10
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import java.net.URL;
import java.util.Set;
import java.util.regex.Pattern;

Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage("com.superz"))
                .filterInputsBy(FilterBuilder.parsePackages("+com.superz"))
                .setScanners(new ResourcesScanner()));
// 路径规则:正则表达式
Set yamlPathSet = reflections.getResources(Pattern.compile(".*\\.yaml"));
for (String yamlPath : yamlPathSet) {
     URL yamlUrl = ResourceTest.class.getClassLoader().getResource(yamlPath);
     System.out.println(yamlUrl);
     // 获取InputStream
     this.getClass().getClassLoader().getResourceAsStream(yamlPath);
}

 注:文件放置在java目录下,需要配置maven(放在resources目录下则不需要)


   
       
           src/main/java
           
               **/*.xml
               **/*.yaml
           
           true
       
   

你可能感兴趣的:(Java)