public class FileUtil {
private final static String JSON_PATH = “./json/”;
/***
* 重新生成配置文件,会将之前的文件重命名
* @param object List<Map>
* @param fileName
*/
public static void buildJsonFile(Object object, String fileName) {
try {
File dic = new File(JSON_PATH);
if (!dic.exists()) {
dic.mkdir();
}
String url = JSON_PATH + fileName;
File file = new File(url);
if (file.exists()) { // 如果已存在,重命名旧文件
String date = DateFormatUtils.format(new Date(), “yyyyMMddHHmmss”);
File newFile = new File(url + “_” + date);
file.renameTo(newFile);
// file.delete();
}
Writer writer = new OutputStreamWriter(new FileOutputStream(file), “UTF-8”);
writer.write(JSONObject.toJSONString(object));
writer.flush();
writer.close();
} catch (Exception e) {
log.info(e.getMessage());
log.error(“json文件生成失败”);
}
}
// json文件路径获取对应String
public static String getMagicConfig(String fileName) {
String url = JSON_PATH + fileName;
File file = new File(url);
if (!file.exists()) {
return “”;
}
try {
FileInputStream fis = new FileInputStream(file);
return readJsonFile(fis);
} catch (FileNotFoundException e) {
log.error(“未找到文件, {}”, url);
}
return “”;
}
public static String readJsonFile(InputStream is) {
String jsonStr = “”;
try {
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
int ch = 0;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}