Java ClassPathResource读取JAR包中的资源方式
更新时间:2026年05月25日 10:41:45 作者:Full Stack Developme
这段描述主要介绍了如何使用ClasspathResource类读取jar包中的资源文件,特别强调了如何读取resources目录下的JSON文件,并分享了个人的自测经验
叙述
使用 ClassPathResource类 读取 jar 包中的资源文件。
自测100%可用。
环境
要读取 resources 目录下的 JSON 文件,如图:


包完整路径:
org.springframework.core.io
代码
/**
* 读取json文件,返回json串
*/
private String readJsonFile() {
BufferedReader reader = null;
String content = "";
try {
ClassPathResource resource = new ClassPathResource("unitMapping.json");
reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
content = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (Exception e) {
logger.error("接口【DictionaryService getUnitMapping】异常参数:" + e);
} finally {
try {
if (null != reader) {
reader.close();
}
} catch (IOException e) {
logger.error("接口【DictionaryService getUnitMapping】异常参数:" + e);
}
}
return content;
}测试

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。


最新评论