广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >java 读取json文件的2种方式
  • 266
分享到

java 读取json文件的2种方式

javajsonlinux 2023-08-18 21:08:46 266人浏览 独家记忆
摘要

1 背景介绍 研发过程中,经常会涉及到读取配置文件等重复步骤,也行是.conf文件,也许是.JSON文件,但不管如何他们最终都需要进入到jave的inputStream里面。下面以读取.json文件为例 2 FileInputStream读

1 背景介绍

研发过程中,经常会涉及到读取配置文件等重复步骤,也行是.conf文件,也许是.JSON文件,但不管如何他们最终都需要进入到jave的inputStream里面。下面以读取.json文件为例

2 FileInputStream读取

需要1个参数:
fileName: 文件名,一般为绝对路径,不然可能会找不到。或者和java文件同一个路径下

static String readWithFileInputStream(){        String jsonString;                //System.getProperty("user.dir")为获取根目录                //File.separator为不同操作系统的分隔符,linux和win是不一样的                //tempFilePath该字符串里面为我们配置文件的路径               String fileName = "xx_config.json";//                String tempFilePath = System.getProperty("user.dir") + File.separator + "resource" + File.separator + fileName;//                System.out.print(tempFilePath);        StringBuilder sb = new StringBuilder();                try{                    InputStream input = new FileInputStream(fileName);                    byte[] buffer = new byte[1024];                    int length = 0;                    length = input.read(buffer);                    while(length != -1){                        sb.append(new String(buffer, 0 , length));                        length = input.read(buffer);                    }                }catch (Exception e){                    e.printStackTrace();                }        return    jsonString = sb.toString();            }      

最终返回一个String。然后通过JSON工具就可以转为自己想读取到模型啦。

    TargetConfig config = (TargetConfig) JSON.parseObject(jsonString, TargetConfig.class);            

但该种方式不灵活,需要把路径写死,或者写成绝对路径。

3 ClassLoader读取

需要2个参数:
fileName: 文件名
ClassLoader: 类加载器,一般为当前类

    static String readWithClassLoader() throws IOException {        String fileName = "xx_config.json";       ClassLoader  classLoader =  TargetConfig.class.getClassLoader();        BufferedReader reader = null;            InputStream inputStream = classLoader.getResourceAsStream(fileName);            reader = new BufferedReader(new InputStreamReader(inputStream));            StringBuilder content = new StringBuilder();            String line = reader.readLine();            while (!StringUtil.isEmpty(line)) {                content.append(line);                line = reader.readLine();            }            return content.toString();    }
      和之前一样,最终返回一个String。然后通过JSON工具就可以转为自己想读取到模型啦。
    TargetConfig config = (TargetConfig) JSON.parseObject(jsonString, TargetConfig.class);            

但使用类加载读取,可以不用写死路径。比第一种要灵活很多。
在这里插入图片描述

来源地址:https://blog.csdn.net/qq_39463175/article/details/130456989

--结束END--

本文标题: java 读取json文件的2种方式

本文链接: https://www.lsjlt.com/news/374799.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作