关于springboot:Springboot-读取修改json配置文件

33次阅读

共计 1950 个字符,预计需要花费 5 分钟才能阅读完成。

读取或更新 resources 下的 json 文件;

{
  "links": [
    {
      "name": "MYSQL_HOST",
      "title": "MYSQL_HOST",
      "content": "127.0.0.1"
    },
    {
      "name": "MYSQL_PORT",
      "title": "端口",
      "content": "3306"
    },
    {
      "name": "MYSQL_DBNAME",
      "title": "数据库",
      "content": "tableau"
    },
    {
      "name": "MYSQL_USER",
      "title": "用户名",
      "content": "root"
    },
    {
      "name": "MYSQL_PASSWORD",
      "title": "明码",
      "content": "123456"
    }
  ]
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Profile;
import java.io.*;
import java.util.HashMap;

public class JsonUtils {public static String readJSON(String fileName) throws Exception {String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));

        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = reader.readLine()) != null) {sb.append(line);
        }
        String result = sb.toString().replaceAll("\r\n", "").replaceAll(" +","");

        return result;
    }

    public static void updateJSON(String fileName, HashMap<String, String> map) throws Exception {JSONObject jsonObject = JSON.parseObject(readJSON(fileName));
        JSONArray links = jsonObject.getJSONArray("links");

        for (int i = 0; i < links.size(); i++) {JSONObject item1 = links.getJSONObject(i);
            if (item1.getString("name").equalsIgnoreCase(map.get("name"))) {item1.put("content", map.get("content"));
            }
        }

        JSONObject nItem = new JSONObject();
        nItem.put("links", links);
        String nContent = JSON.toJSONString(nItem);

        String filePath = Profile.class.getClassLoader().getResource(fileName).toURI().getPath();

        BufferedWriter bw = null;
        try {bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));
            bw.write("");
            bw.write(nContent);
            bw.close();} catch (IOException e) {e.printStackTrace();
        } finally {
            try {bw.close();
            } catch (IOException e) {e.printStackTrace();
            }
        }

    }
}
    @PostMapping()
    public ResponseEntity<Object> editConfig(@RequestBody HashMap<String, String> map) throws Exception {JsonUtils.updateJSON("user.json", map);

        return new ResponseEntity<>(HttpStatus.OK);
    }

正文完
 0