解决:java 读取 resources 下面的 json 文件
前言: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/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.json</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
以上是 解决:java 读取 resources 下面的 json 文件 的全部内容, 来源链接: utcz.com/z/390814.html