解決:java 讀取 resources 下面的 json 文件
阿新 • • 發佈:2018-09-28
println 字符 ces 配置文件 trac all .json pro tst
前言: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 文件