栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中打包发布后无法读取json文件问题浅析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot中打包发布后无法读取json文件问题浅析

springboot工程中读取json文件是一个非常常见的操作,在本地idea运行调试的时候读取json文件没有任何问题,但是打包发布后运行会报读取不到json文件的问题,解决方法如下

  • 要将json文件放到static目录下,如/static/config/
  • 读取json文件要用ClassPathResource和fastJson操作
    示例:
// 1
ClassPathResource resource = new ClassPathResource("static/config/Info.json");
// 2
JSONObject jsonObject = JSONObject.parseObject(FileUtil.readJson(resource ));
// 3
public static String readJson(ClassPathResource classPathResource) {
        String jsonStr = "";
        try {
            InputStream inputStream = classPathResource.getInputStream();
            Reader reader = new InputStreamReader(inputStream, "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
// 4
jsonObject .get("");

这样即可在打包运行时正确读取json文件,并转成json对象进行后续操作。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/827341.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号