对象json文件转换

  • Post author:
  • Post category:其他


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;

}

}

}



版权声明:本文为bighacker原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。