properties配置文件读写操作工具类

java对properties配置文件的读写操作工具类:

代码如下:

 

package com.syxp.moa.message.weiguiwailian.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * properties文件读写操作工具类
 * @author 常宝龙
 *
 */
public class ReadWriteTools {

	//属性文件路径
	private static String propertiesPath ;
	private static Logger logger = Logger.getLogger(ReadWriteTools.class);
	static {
		//获取当前路径
		propertiesPath=System.getProperty("user.dir")+"/conf/weiguilianjie.properties";
	}
	
	/**
	 * 根据主键key读取主键的值value
	 * @param key:键
	 * @param filePath:属性文件路径
	 */
	
	public static String readValue(String propertiesPath,String key){
		Properties properties = new Properties();
		try{
			InputStream is = new BufferedInputStream(new FileInputStream(propertiesPath));
			properties.load(is);
			String value = properties.getProperty(key);
			is.close();
			return value;
		}catch(Exception e){
			logger.error("读取配置文件键值发生错误!",e);
			return null;
		}
	}
	
	/**
	 * 根据主键key读取主键的值value
	 * @param key:键
	 */
	
	public static String readValue(String key){
		Properties properties = new Properties();
		try{
			InputStream is = new BufferedInputStream(new FileInputStream(propertiesPath));
			properties.load(is);
			String value = properties.getProperty(key);
			is.close();
			return value;
		}catch(Exception e){
			logger.error("读取配置文件键值发生错误!",e);
			return null;
		}
	}
	
	/**
	 * 更新(或插入)一对properties信息(主键及其键值)
	 * 如果该主键已经存在,更新该主键的值;
	 * 如果该主键不存在,则插件一对键值。
	 * @param keyName:键名
	 * @param keyValue:键值
	 */
	
	public static void writeProperties(String keyName,String keyValue){
		try{
			// 调用 HashTable 的方法 put,使用 getProperty 方法提供并行性。
            // 强制要求为属性的键和值使用字符串。返回值是 HashTable 调用 put 的结果。
			//读配置文件路径
			Properties properties = new Properties();
			properties.load(new FileInputStream(propertiesPath));
			OutputStream os = new FileOutputStream(propertiesPath);
			properties.setProperty(keyName, keyValue);
			 // 以适合使用 load 方法加载到 Properties 表中的格式,
            // 将此 Properties 表中的属性列表(键和元素对)写入输出流
			properties.store(os, "Update '" + keyName + "' value");
			os.close();
		}catch(FileNotFoundException e){
			logger.error("配置文件路径没有找到!",e);
		}catch(IOException e){
			logger.error("属性文件更新错误",e);
		}finally{
		
		}
	}
	
	//测试代码
	
	public static void main(String[] args) {
		System.out.println("readValue==" + readValue("id"));
		writeProperties("id", "5");
		System.out.println("readValue==" + readValue("id"));
		System.out.println("更新配置文件成功!");
	}
}

 

此例子中,properties配置文件需要放在classpath下的conf目录中,并且其中包含id 这个key

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值