Files
biliob/src/main/java/com/yutou/bilibili/Tools/ConfigTools.java
Yutousama 00c049573e ConfigTools新增读取配置方法
修复没有配置文件时,QQbot无法初始化的问题
2022-04-11 11:56:23 +08:00

92 lines
2.6 KiB
Java

package com.yutou.bilibili.Tools;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
/**
* 配置和参数
*/
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){
com.yutou.bilibili.Tools.Log.e(e);
}
}
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 = JSONObject.parseObject(src);
return json.getObject(key, t);
} catch (Exception e) {
}
}
return def;
}
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=JSONObject.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) {
com.yutou.bilibili.Tools.Log.e(e);
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) {
Log.i("error = "+file.getAbsolutePath());
com.yutou.bilibili.Tools.Log.e(e);
}
return null;
}
}