All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yes.tools.generator.utils.JsonIoUtils Maven / Gradle / Ivy

There is a newer version: 2.0.4
Show newest version
package org.yes.tools.generator.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.yes.tools.core.exception.YesBaseException;
import org.yes.tools.utils.BeanCopyUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Co.
 * @name JsonIoUtils
 * @date 2023/4/4 0:02
 */
public class JsonIoUtils {


    /**
     * 获取json文件
     *
     * @param filePath
     * @param 
     * @return
     */
    public static  List getFileJson(String filePath, Class destType) {
        String property = System.getProperty("user.dir");
        String path = property + "/" + filePath;
        File targetFile = new File(path);
        if (targetFile.exists()) {
            String jsonStr = readJsonFile(path);
            JSONArray result = JSONObject.parseArray(jsonStr);
            return BeanCopyUtils.copyListAs(result, destType);
        }
        return new ArrayList();
    }

    /**
     * 保存json文件
     *
     * @param filePath
     * @param list
     */
    public static void saveFileJson(String filePath, List list) {
        String property = System.getProperty("user.dir");
        String path = property + "/" + filePath;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            OutputStreamWriter writer = new
                    OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
            writer.write(String.valueOf(JSONObject.toJSONString(list)));
            writer.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new YesBaseException("保存文件失败");
        }
    }


    public static String readJsonFile(String filePath) {
        String jsonStr = "";
        try {
            File jsonFile = new File(filePath);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), 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;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy