Files
nas-service/src/main/java/com/yutou/nas/utils/ConfigTools.java
2022-05-03 20:08:51 +08:00

120 lines
3.2 KiB
Java

package com.yutou.nas.utils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
/**
* 配置和参数
*/
public class ConfigTools {
public static final String CONFIG = "config.json";
public static final String DATA = "data.json";
public static final String SQLITE = "sqlite.json";
static {
try {
File file = new File(CONFIG);
if (!file.exists()) {
file.createNewFile();
}
file = new File(DATA);
if (!file.exists()) {
file.createNewFile();
}
file = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object load(String type, String key) {
return load(type, key, Object.class, null);
}
public static <T> T load(String type, String key, Class<T> t) {
return load(type, key, t, null);
}
public static <T> T load(String type, String key, Class<T> t, T def) {
File file = new File(type);
//com.yutou.nas.utils.Log.i(type+"配置文件地址:"+file.getAbsolutePath());
String src = readFile(file);
if (src != null) {
try {
JSONObject json = JSON.parseObject(src);
return json.getObject(key, t);
} catch (Exception e) {
}
}
return def;
}
public static String loadIni(File file, String key) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp, str = null;
while ((tmp = reader.readLine()) != null) {
if(tmp.startsWith(key+"=")){
str=tmp.split("=")[1];
if(StringUtils.isEmpty(str)){
str=null;
}
break;
}
}
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean save(String type, String key, Object data) {
File file = new File(type);
String src = readFile(file);
if (src == null) {
src = "{}";
}
JSONObject json = JSON.parseObject(src);
json.put(key, data);
saveFile(file, json.toJSONString());
return false;
}
public static boolean saveFile(File file, String data) {
try {
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.flush();
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static String readFile(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp;
StringBuilder str = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
str.append(tmp);
}
reader.close();
return str.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}