java 讀寫 json 配置文件工具類

如下conf.json文件:

{
    "initStep": 2,
    "isInit": 0,
    "isReboot": 0,
    "caServerConf": {
        "caServerIp": "11.12.110.83",
        "caServerPort": "8080",
        "trustCertName": "user0111.p7b"
    }
}

 轉成java類:

package com.xdja.pki.ra.core.common.config;

import com.xdja.pki.ra.core.util.file.FileUtils;
import com.xdja.pki.ra.core.util.json.JsonMapper;
import org.apache.commons.lang3.StringUtils;

/**
 * 初始化配置文件 conf.json
 *
 * @author wly
 *
 */
public class Config {

    /**
     * 初始化步驟數
     */
    private int initStep;

    /**
     * 是否初始化 //0未初始化  1 已初始化
     */
    private int isInit;

    /**
     * 是否完成重啓 //0未初始化  1 已初始化
     */
    private int isReboot;

    /**
     * CA服務配置信息
     */
    private CaServerConf caServerConf;

    public int getInitStep() {
        return initStep;
    }

    public void setInitStep(int initStep) {
        this.initStep = initStep;
    }

    public int getIsInit() {
        return isInit;
    }

    public void setIsInit(int isInit) {
        this.isInit = isInit;
    }

    public int getIsReboot() {
        return isReboot;
    }

    public void setIsReboot(int isReboot) {
        this.isReboot = isReboot;
    }


    public CaServerConf getCaServerConf() {
        return caServerConf;
    }

    public void setCaServerConf(CaServerConf caServerConf) {
        this.caServerConf = caServerConf;
    }

    @Override
    public String toString() {
        return "Config{" +
                "initStep=" + initStep +
                ", isInit=" + isInit +
                ", isReboot=" + isReboot +       
                ", caServerConf=" + caServerConf +
                
                '}';
    }

    /**
     * 獲取配置信息
     *
     * @param path 配置文件全路徑
     * @return 配置文件對象
     */
    public static Config getConfig(String path) {
        if (StringUtils.isBlank(path)) {
            return null;
        }

        try {
            String content = FileUtils.read(path);

            if (StringUtils.isBlank(content)) {
                return null;
            }

            return JsonMapper.alwaysMapper().fromJson(content, Config.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 保存配置信息
     *
     * @param config 配置信息
     * @param path   配置文件全路徑
     * @throws Exception
     */
    public static void saveConfig(Config config, String path) throws Exception {
        if (null == config) {
            throw new IllegalArgumentException("配置文件不能null");
        }

        FileUtils.save(JsonMapper.alwaysMapper().toJson(config), path);
    }
}
package com.xdja.pki.ra.core.common.config;

/**
 * CA服務配置信息
 *
 * @author wly
 */
public class CaServerConf {
    /**
     * "caServerConf": {
     * "caServerIp": "22.22.22.22",
     * "caServerPort": "8080",
     * "trustCertName": "trustCert.p7b"
     * },
     */

    /**
     * 服務ip地址
     */
    private String caServerIp;
    /**
     * 服務端口
     */
    private String caServerPort;
    /**
     * CA證書鏈文件名
     */
    private String trustCertName;

    public String getCaServerIp() {
        return caServerIp;
    }

    public void setCaServerIp(String caServerIp) {
        this.caServerIp = caServerIp;
    }

    public String getCaServerPort() {
        return caServerPort;
    }

    public void setCaServerPort(String caServerPort) {
        this.caServerPort = caServerPort;
    }

    public String getTrustCertName() {
        return trustCertName;
    }

    public void setTrustCertName(String trustCertName) {
        this.trustCertName = trustCertName;
    }

    @Override
    public String toString() {
        return "caServerConf{" +
                "caServerIp='" + caServerIp + '\'' +
                ", caServerPort=" + caServerPort +
                ", trustCertName='" + trustCertName + '\'' +
                '}';
    }
}
public class FileUtils {

    protected static transient final Logger logger = LoggerFactory.getLogger(FileUtils.class.getClass());

    /**
     * 讀取文件內容
     *
     * @param path 完整文件路徑
     * @return 文件內容字符串
     * @throws Exception
     */
    public static String read(String path) throws Exception {
        StringBuilder content = new StringBuilder();
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(new File(path)));

            String temp;

            while (null != (temp = reader.readLine())) {
                content.append(temp);
            }

            return content.toString();
        } catch (Exception e) {
            logger.error("讀取文件異常", e);
            throw e;
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("讀取文件時流關閉異常", e);
                }
            }
        }
    }
}
/**
 * JSON操作工具類
 * 
 * @author wyf
 *
 */
public class JsonMapper {
	
	/**
	 * 輸出所有屬性到Json字符串
	 */
	private static final JsonMapper alwaysMapper = new JsonMapper();
	/**
	 * 獲取輸出所有屬性到Json字符串的Mapper
	 */
	public static JsonMapper alwaysMapper() {
		return alwaysMapper;
	}
        private ObjectMapper mapper;

        private JsonMapper() {
        this(null);
        }

        private JsonMapper(JsonInclude.Include include) {
        mapper = new ObjectMapper();
        // 設置輸出時包含屬性的風格
        if (include != null) {
            mapper.setSerializationInclusion(include);
        }
        // 設置輸入時忽略在JSON字符串中存在但Java對象實際沒有的屬性
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        mapper.getFactory().enable(JsonParser.Feature.ALLOW_COMMENTS);
        mapper.getFactory().enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        }
	
	/**
	 * 	
	 * 轉換json字符串爲指定對象
	 * @param jsonString
	 * @param clazz
	 * @return
	 * @throws JSONException
	 */
	public <T> T fromJson(String jsonString, Class<T> clazz) throws JSONException {
		try {
			return mapper.readValue(jsonString, clazz);
		} catch (Exception t) {
			throw new JSONException("把json字符串轉換爲指定類型的對象出錯(" + t.getMessage() + ")", t);
		}
	}
    /**
	 * 
	 * 把obj轉換爲json字符串
	 * @param obj
	 * @return
	 * @throws JSONException
	 */
	public String toJson(Object obj) throws JSONException {
		if (obj == null) {
            return "{}";
        } else {
        	try {
        		return mapper.writeValueAsString(obj);
        	} catch (Exception t) {
                throw new JSONException("把obj轉換爲json字符串出錯(" + t.getMessage() + ")", t);
            }
        }
	}
}

讀寫:

 
        Result result = new Result();
        //獲取文件名
        String trustCertName = file.getOriginalFilename();
        //修改CA服務配置文件
        try {
            Config config = Config.getConfig(path);
            //修改步驟數
            config.setInitStep(2);
            //修改CA服務信息
            CaServerConf caServerConf = config.getCaServerConf();
            caServerConf.setCaServerIp(caServerIp);
            caServerConf.setCaServerPort(caServerPort);
            caServerConf.setTrustCertName(trustCertName);
            Config.saveConfig(config, path);
        } catch (Exception e) {
            logger.error("配置CA服務操作config.json異常", e);
            result.setError(ErrorEnum.CONFIG_JSON_FILE_OPERATION_ERROR);
            return result;
        }

前段時間畢業事宜請了長假,回公司之後提測之前的功能又開發新功能,剛剛忙完,又來記錄我的學習筆記啦!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章