解决:java 读取 resources 下面的 json 文件
2021-06-17 19:04
阅读:615
标签:直接 配置 .json classpath package char 类型 工具 static
前言:java 读取 工程下的配置文件,文件类型为 json(*.json),记录一下始终读取不到 json 文件的坑。maven项目
直接上工具类代码
package com.yule.component.dbcomponent.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import java.io.*; /** * 配置文件工具类 * @author yule * @date 2018/9/28 16:26 */ public class PropertiesUtils { private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class); /** * 读取json文件,返回json字符串 * @param fileName * @return */ public static String readJsonFile(String fileName) { FileReader fileReader = null; Reader reader = null; try { File jsonFile = ResourceUtils.getFile("classpath:"+fileName); fileReader = new FileReader(jsonFile); reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8"); int ch; StringBuffer sb = new StringBuffer(); while ((ch = reader.read()) != -1) { sb.append((char) ch); } fileReader.close(); reader.close(); String jsonStr = sb.toString(); return jsonStr; } catch (IOException e) { e.printStackTrace(); logger.error("读取文件报错", e); } finally { if(fileReader != null){ try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
调用方式:
limit.json 项目路径为 resources->conf->system->limit.json
String json = PropertiesUtils.readJsonFile("conf/system/limit.json");
System.out.println(json);
注意:
我在开发中遇到一个坑,始终读取不到 json 文件,报错,是因为 pom.xml 文件里面没有配置:
resources>
resource>
directory>src/main/javadirectory>
includes>
include>**/*.xmlinclude>
includes>
filtering>truefiltering>
resource>
resource>
directory>src/main/resourcesdirectory>
includes>
include>**/*.propertiesinclude>
include>**/*.xmlinclude>
**/*.json
includes>
filtering>truefiltering>
resource>
resources>
解决:java 读取 resources 下面的 json 文件
标签:直接 配置 .json classpath package char 类型 工具 static
原文地址:https://www.cnblogs.com/yuxiaole/p/9719954.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:解决:java 读取 resources 下面的 json 文件
文章链接:http://soscw.com/essay/95171.html
文章标题:解决:java 读取 resources 下面的 json 文件
文章链接:http://soscw.com/essay/95171.html
评论
亲,登录后才可以留言!