Construction JsonUtil class, contains two methods, respectively, for storing information and read the local json json.
/**
* 读取与写入JSON文件
* */
public class NodeJsonUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJsonUtil.class);
// 将Nodes信息保存到本地json文件中
public static void saveJson(ConvertDiagram jsonDiagram, String filePath){
String writeString = JSON.toJSONString(jsonDiagram, SerializerFeature.PrettyFormat);
LOGGER.info(writeString);
BufferedWriter writer = null;
File file = new File(filePath);
//如果文件不存在则新建
if (!file.exists()){
try {
file.createNewFile();
}catch (IOException e){
LOGGER.error(e.getMessage());
}
}
//如果多次执行同一个流程,会导致json文件内容不断追加,在写入之前清空文件
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false),"UTF-8"));
writer.write("");
writer.write(writeString);
}catch (IOException e){
LOGGER.error(e.getMessage());
}finally {
try{
if (writer != null){
writer.close();
}
}catch (IOException e){
LOGGER.error(e.getMessage());
}
}
}
// 用于读取JSON文件
public static readJsonFile(String filePath){
BufferedReader reader = null;
String readJson = "";
try {
FileInputStream fileInputStream = new FileInputStream(filePath);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
String tempString = null;
while ((tempString = reader.readLine()) != null){
readJson += tempString;
}
}catch (IOException e){
LOGGER.error(e.getMessage());
}finally {
if (reader != null){
try {
reader.close();
}catch (IOException e){
LOGGER.error(e.getMessage());
}
}
}
// 获取json
try {
JSONObject jsonObject = JSONObject.parseObject(readJson);
System.out.println(JSON.toJSONString(jsonObject));
}catch (JSONException e){
LOGGER.error(e.getMessage());
}
}
}