package util.sqlparse.visitor.dm.test;

import com.chenyang.fastjson.JSON;
import com.chenyang.fastjson.JSONObject;
import com.chenyang.fastjson.serializer.SerializerFeature;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class JsonUtil {
   public static String readJson(String path) {
      File file = new File(path);
      BufferedReader br = null;
      StringBuffer data = new StringBuffer();

      try {
         br = new BufferedReader(new FileReader(file));
         String temp = null;

         while((temp = br.readLine()) != null) {
            data.append(temp);
         }
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (br != null) {
            try {
               br.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }

      }

      return data.toString();
   }

   public static void writeJson(String path, JSONObject json, String fileName) {
      BufferedWriter bw = null;
      File file = new File(path + fileName);
      if (!file.exists()) {
         try {
            file.createNewFile();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      try {
         bw = new BufferedWriter(new FileWriter(file));
         String jsonString = JSON.toJSONString(json, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
         bw.write(jsonString);
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            if (bw != null) {
               bw.close();
            }
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

      System.out.println("写入成功！");
   }
}
