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;
        }

前段时间毕业事宜请了长假,回公司之后提测之前的功能又开发新功能,刚刚忙完,又来记录我的学习笔记啦!!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值