SpringBoot项目读取json格式文件配置
方式一、
项目结构:
import org.springframework.core.io.Resource; import org.springframework.util.ResourceUtils; @Value("classpath:config.json") private Resource resource; private static void parseJson(){ try{ //File filePath = resource.getFile();//第一种 File filePath = ResourceUtils.getFile("classpath:config.json");//第二种 String jsonData = FileUtils.readFileToString(filePath, "UTF-8"); JSONObject conJson = JSONObject.parseObject(jsonData); System.out.println("data:"+conJson.toJSONString()); }catch (IOException e){ System.out.println(("config analysis is error...")); e.printStackTrace(); } }
方式二、
注:配置文件与jar分离打包后使用方法!!!
项目结构:
@Value("${basic.jsonPath}")
private String jsonPath;
private static void parseJson() {
try {
String path = System.getProperty("user.dir");//获取项目路径
String filePath = String.format("%s%s", path, jsonPath);//获取json文件路径,进行完整拼接:/config/config.json
System.out.println(("Json File Path:[{}]..." + filePath));
String jsonData = FileUtils.readFileToString(new File(filePath), "UTF-8");
JSONObject conJson = JSONObject.parseObject(jsonData);
System.out.println("查询数据库用户信息为:" + conJson.toJSONString());
} catch (IOException e) {
System.out.println(("config analysis is error..."));
e.printStackTrace();
}
}
参考链接一、、