springboot读取json文件进行增删操作

springboot读取json文件进行增删操作

1.读文件

public static JSONArray read(String Path)throws Exception {
        BufferedReader reader = null;
        JSONArray ret = null;
        JSONArray arr = new JSONArray();
        try{
            File file = new File(Path);
            FileInputStream resource = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(resource));
            StringBuilder builder = new StringBuilder();
            String line ="";
            while((line = reader.readLine())!=null) {
                builder.append(line);
            }
            ret =  JSON.parseArray(builder.toString());
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(reader!=null){
                reader.close();
            }
        }
        return arr;
    }

在此,filePath可以是本地文件路径(如:C:\xxx.json),也可以是项目中文件路径(src/main/xxx)路径一定要对哦

2.增加操作

此处传递一个可以转换成为JSONAObject的String字符串

public static JSONArray insert(String str, JSONArray arr){
        arr.add(JSONObject.parseObject(str));
        return arr;
	}

此处传递的参数arr即是从上面读文件的操作中得到的JSONArray数组,可以直接通过传参的形式传递过来使用

3.删除操作

此处可以传递一个类似于数据库主键的数据(我这里传递的是id的值),利用迭代器,进行删除操作

public static JSONArray delete(String id, JSONArray arr)throws Exception {
        Iterator<Object> it = arr.iterator();
        while(it.hasNext()){
            JSONObject x = (JSONObject)it.next();
            if(x.getString("id").equals(id)){
                it.remove();
            }
        }
        return arr;
    }

此处传递的参数arr即是从上面读文件的操作中得到的JSONArray数组,可以直接通过传参的形式传递过来使用

4.写入文件

将进行插入或者删除操作后的数据存入json文件中

public static void write(JSONArray arr, String Path) throws Exception {
        BufferedWriter writer = null;
        try {
            String s= JSON.toJSONString(arr, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);
            File file = new File(Path);
            FileOutputStream resource = new FileOutputStream(file, false);
            writer = new BufferedWriter(new OutputStreamWriter(resource));
            writer.write(s);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(writer!=null){
                writer.close();
            }
        }
    }

OK,大功告成

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值