Properties 工具类

package com.gulf.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;


/**
 * 
 * @Description:用于从配置文件中读取信息
 * @author gulf
 * @date 2014年9月23日
 */
public class PropertiesUtil {
    
    private static Logger logger = Logger.getLogger(PropertiesUtil.class.getName());
    /**
     * 根据key获得value
     * @param key
     * @return value
     * @throws IOException 
     */
    public static String getValue(String resourceString,String key) throws IOException {
        String value="";
        Resource resource = new ClassPathResource(resourceString);
        try {
            Properties props = PropertiesLoaderUtils.loadProperties(resource);
            value=props.getProperty(key);
        } catch (IOException e) {
            logger.error("读取配置文件失败", e);
            throw new IOException("读取配置文件失败");
        }
        return value;
    }
    /**
     * 更新配置文件
     * @param key
     * @param value
     * @throws IOException
     */
    public static void setValue(String key,String value) throws IOException{
        try{
            Resource resource = new ClassPathResource("/config.properties");
            Properties props = PropertiesLoaderUtils.loadProperties(resource);
            OutputStream fos = new FileOutputStream(resource.getFile());
            props.setProperty(key, value);
            props.store(fos, "update"+key);
        }catch(Exception e){
            logger.error("写入配置文件失败", e);
            throw new IOException("写入配置文件失败");
        }
        
    }
    
}
 

转载于:https://my.oschina.net/chendongj/blog/898875

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值