java 读取json文件的2种方式

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);
            

但使用类加载读取,可以不用写死路径。比第一种要灵活很多。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年12月7日
下一篇 2023年12月7日

相关推荐