天天看點

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

}