读取修改resource文件夹下的json文件

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.context.annotation.Profile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class ConfigFileUtils {
    //文件名
	public static final String FILE_NAME = "config.json";

    public static JSONObject readAllConfig() throws Exception {
        String filePath = Profile.class.getClassLoader().getResource(FILE_NAME).toURI().getPath();
        return JSONUtil.readJSONObject(new File(filePath),StandardCharsets.UTF_8);
    }

	public static JSONObject readConfig(String config) throws Exception {
		String filePath = Profile.class.getClassLoader().getResource(FILE_NAME).toURI().getPath();
		JSONObject jsonObject = JSONUtil.readJSONObject(new File(filePath),StandardCharsets.UTF_8);
		JSONArray configs = jsonObject.getJSONArray(config);
		return configs.getJSONObject(0);
	}

	public static void updateConfig(String config, Map<String, Object> map) throws Exception {
		String filePath = Profile.class.getClassLoader().getResource(FILE_NAME).toURI().getPath();
		JSONObject jsonObject = JSONUtil.readJSONObject(new File(filePath),StandardCharsets.UTF_8);
		JSONArray configs = jsonObject.getJSONArray(config);

		JSONObject item1 = configs.getJSONObject(0);
		for (String s : map.keySet()) {
			item1.set(s,map.get(s));
		}
		configs.add(0,item1);
		jsonObject.set(config,configs);
		String nContent = JSONUtil.toJsonStr(jsonObject);
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
			bw.write(nContent);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
{
  "elastic": [
    {
      "host": "elasticsearch.enlink.top"
    }
  ],
  "mysql": [
    {
      "host": "mysql.enlink.top",
      "name": "enlink",
      "username": "enlink",
      "password": "enlink"
    }
  ],
  "configs": [
    {
      "elastic": "true",
      "mysql": "true"
    }
  ]
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值