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"
}
]
}
|