加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用FastJson进行JSON文件的读取和写入

发布时间:2020-12-16 18:40:25 所属栏目:百科 来源:网络整理
导读:构建JsonUtil类,包含两个方法,分别用于保存json信息和读取本地json。 /** * 读取与写入JSON文件 * */public class NodeJsonUtil { private static final Logger LOGGER = LoggerFactory.getLogger(NodeJsonUtil.class); // 将Nodes信息保存到本地json文件

构建JsonUtil类,包含两个方法,分别用于保存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());
        }
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读