欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

# 获取类路径资源 ResourcePatternResolver&PathMatchingResourcePatternResolver

最编程 2024-03-30 13:48:43
...
【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”

ResourcePatternResolver介绍

用于解析资源文件的策略接口,其特殊的地方在于,它应该提供带有*号这种通配符的资源路径。此接口是ResourceLoader接口的拓展接口。

源码:

public interface ResourcePatternResolver extends ResourceLoader {

	/**
	 * 在所有根目录下搜索文件的伪URL的前缀
	 * 与ResourceLoader中classpath不同的地方在于,此前缀会在所有的JAR包的根目录下搜索指定文件。
	 * @see org.springframework.core.io.ResourceLoader#CLASSPATH_URL_PREFIX
	 */
	String CLASSPATH_ALL_URL_PREFIX = "classpath*:";

	/**
	 * 返回指定路径下所有的资源对象。
	 * 返回的对象集合应该有Set的语义,也就是说,对于同一个资源,只应该返回一个资源对象
	 * @param locationPattern the location pattern to resolve
	 * @return the corresponding Resource objects
	 * @throws IOException in case of I/O errors
	 */
	Resource[] getResources(String locationPattern) throws IOException;

}

 

 

1. 读取resource下的文件

@Autowired
private ResourcePatternResolver resourcePatResolver;

private List<String> forestsName = new ArrayList<>();

@PostConstruct
private void postConstructInit() throws Exception {

    //加载自定义词典
    for(Resource resource:  resourcePatResolver.getResources("classpath:dics/userLibrary/*.dic")) {
       //TODO 
       Forest forest = Library.makeForest(resource.getInputStream());

       String key = "dic_" + resource.getFilename().replace(".dic", "");
       DicLibrary.put(key, key, forest);
       forestsName.add(key);
    }
}

 

PathMatchingResourcePatternResolver介绍

PathMatchingResourcePatternResolver是一个Ant模式通配符的Resource查找器,可以用来查找类路径下或者文件系统中的资源。

1. 加载当前类路径中所有匹配的资源

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

//classpath: 表示加载当前类路径中所有匹配的资源
Resource[] resources = resourcePatternResolver.getResources("classpath:dics/userLibrary/*.dic");
for(Resource r : resources){
    // 文件名
    System.out.println(r.getFilename());
    // 文件绝对路径
    System.out.println(r.getURL().getPath());
    // File对象
    System.out.println(r.getFile());
    // InputStream对象
    System.out.println(r.getInputStream());
}

2. 加载类路径中所有匹配的资源

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

// classpath*: 表示加载类路径中所有匹配的资源
resources = resourcePatternResolver.getResources("classpath*:com/haodf/**/*.class");
for(Resource r : resources){
    // 文件绝对路径
    System.out.println("文件绝对路径:" + r.getURL().getPath());
}

3. 加载文件系统中的资源

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

// 加载文件系统中的资源
Resource r = resourcePatternResolver.getResource("file:/Users/lihuan/Documents/projects/git/me/default.dic");
// 读取文件内容
System.out.println("读取文件内容:" + r.getInputStream());

 

 

推荐阅读