天天看点

java属性文件读取

package com.ep.messageservice.base;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;


/**
 * java属性文件读取,存储帮助类,处理properties文件的读取及存储等等
 * 
 * @author wustrive_2008
 * @date 2012-9-5
 * @time 下午05:45:32
 * @version 1.1
 * @tags
 */
public class PropertyReader {
	private Logger log = Logger.getLogger(PropertyReader.class);
	/**
	 * 处理的文件路径
	 */
	private String propertyFile = "";

	/**
	 * 默认的文件名称
	 * 得到的当前类的绝对路径用“WEB-INF”作为分隔符分割,最后再最追加上WEB-INF/
	 */
	private static String projectPath = PropertyReader.getPathFromClass(PropertyReader.class).split("WEB-INF")[0]+"WEB-INF/";
	
	private static String defaultConfigFileName = projectPath+"config.properties";

	/**
	 * 声明java {@code Properties}对象
	 */
	private Properties property = null;

	/**
	 * 使用默认配制文件加载属性文件
	 */
	public PropertyReader() {
		this(defaultConfigFileName);

	}

	/**
	 * 使用给定的文件,实例化PropertyReader对象,文件的路径为此类的路径
	 * @param f  properties文件路径,包括文件名称,即绝对路径;
	 */
	public PropertyReader(String f) {
		propertyFile = f;
		try {
			property = new Properties();//Properties,该类主要用于读取项目的配置文件(以.properties结尾的文件和xml文件)。 
			FileInputStream fis = new FileInputStream(propertyFile);//读取文件内容以流的形式放到内存当中
			property.load(fis);//加载文件流到自身容器当中,可以解读文件内容;
			fis.close();//关闭从磁盘读取文件内容到内存当中的连接,之后其它对象就无法再使用这个内存当中的文件流了;
		} catch (Exception e) {
			System.out.println("不能正确读取配置文件:" + this.propertyFile + ",错误原因:"
					+ e.getMessage());
			return;
		}
	}

	/**
	 * 给定指定的文件路径及文件名构造PropertyReader对象
	 * 
	 * @param filePath  properties文件路径
	 *           
	 * @param fileName  properties文件名称
	 *            
	 */
	public PropertyReader(String filePath, String fileName) {
		propertyFile = fileName;
		String path = filePath;
		try {
			property = new Properties();//创建一个空的属性列表没有默认值。
			FileInputStream fis = new FileInputStream(path + propertyFile);
			property.load(fis);
			fis.close();
		} catch (Exception e) {
			log.warn("不能正确读取配置文件:" + this.propertyFile + ",错误原因:"
					+ e.getMessage());
			return;
		}
	}

	/**
	 * 得到key所对应的Value,如果没有对应的值返回null.
	 * 
	 * @param key key值
	 *            
	 * @return 得到key对应的Value
	 */
	public String get(String key) {
		String temp = null;
		try {
			temp = property.getProperty(key);
		} catch (Exception e) {
			log.warn("从配置文件中取值出现异常,检查配置文件是否正确。" + e);
		}
		return temp;
	}

	/**
	 * 设置指定key项的值
	 * 
	 * @param key
	 * @param value
	 * @return true/false
	 */
	public boolean set(String key, String value) {
		boolean isSuccess = false;
		if (key != null && !key.trim().equals("")) {
			try {
				property.setProperty(key, value);
				isSuccess = true;
			} catch (Exception e) {
				log.warn("PropertyReader.set()" + e);
			}
		}
		return isSuccess;
	}

	/**
	 * 跟据传入的数据源的配制名字得到数据源的真实名字
	 * 
	 * @param sourceName 要连接数据源的配制名字
	 *            
	 * @return 返回数据源的真实名字
	 * 
	 */
	public String getURL(String sourceName) {
		String value = null;
		try {
			value = get(sourceName + "URL");
		} catch (Exception e) {
			log.warn("PropertyReader.getURL()" + e);
		}
		return value;
	}

	/**
	 * 保存当前加载的Property文件
	 */
	public void stroe() {
		try {
			FileOutputStream fos = new FileOutputStream(propertyFile);
			property.store(fos, propertyFile);
			fos.close();
		} catch (Exception e) {
			log.warn("无法保存配置文件:" + e.getMessage());
		}
	}

	/**
	 * 从Property Map中移除所有映射,调用此方法后property的缓存Map为空
	 */
	public void clean() {
		property.clear();
	}

	/**
	 * 查找配置文件节点是否存在
	 * 
	 * @param key
	 * @return true/false
	 */
	public boolean checkKey(String key) {
		boolean result = false;
		if (!key.equals("") && key != null) {
			try {
				Enumeration<Object> en = property.keys();
				String enKey = "";
				while (en.hasMoreElements()) {
					enKey = (String) en.nextElement();
					if (enKey.equals(key)) {
						result = true;
						break;
					}
				}
			} catch (Exception e) {
				log.warn("查找" + key + "出错:" + e.getMessage());
			}
		}
		return result;
	}

	/**
	 * 增加配置文件节点
	 * 
	 * @param key  节点名称
	 *           
	 * @param value  节点值
	 *           
	 * @return true/false
	 */
	public boolean addElement(String key, String value) {
		log.warn("存储属性文件!!-----------------------!-");
		boolean result = false;
		if (!key.equals("") && key != null) {
			try {
				property.put(key, value);

				result = true;
			} catch (Exception e) {
				// TODO: handle exception
				log.warn("增加节点key出错:" + e.getMessage());
			}
		}
		return result;

	}

	/**
	 * 读取Properties文件的内容,返回Map
	 * 
	 */
	public ConcurrentHashMap<String, String> getPropertiesMap() {
		ConcurrentHashMap<String, String> propertiesMap = new ConcurrentHashMap<String, String>();
		if (property.keySet() != null) {
			for (Iterator<Object> it = property.keySet().iterator(); it
					.hasNext();) {
				String key = (String) it.next();
				String value = (String) property.get(key);
				propertiesMap.put(key, value);
			}
		}
		return propertiesMap;
	}
	/**
	 * 移除指定的key对应的内容
	 * 
	 * @param key
	 * 
	 */
	public void remove(String key) {
		if (property.get(key) != null) {
			property.remove(key);
		}
	}

	/**
	 * 取得class的类路径
	 * 
	 * @param theClass  类名称
	 *         
	 * @return str 路径字符串
	 * 
	 */
	public static String getPathFromClass(Class<? extends Object> theClass) {
		java.net.URL u = theClass.getResource("");
		String str = u.toString();
		str = str.substring(6, str.length());//beginindex,endindex;"hamburger".substring(4, 8) returns "urge"
		str = str.replaceAll("%20", " ");//表达式中的“%20”用“ ”替换
		return str;
	}

}