1. 程式人生 > >解決修改properties 屬性檔案存在快取問題,附帶操作properties檔案工具類

解決修改properties 屬性檔案存在快取問題,附帶操作properties檔案工具類

     在做專案的時候有些資料不一定需要在資料庫管理,例如資料庫連線,定時任務等等的配置..有時候需要動態修改這些資料,但在修改完後,再次獲取時出現問題.

   在專案中要修改properties,修改之後,再進入相關目錄檢視properties檔案,發現內容已經修改了,但是但通過TaskController.class.getResourceAsStream("/config.properties");獲取的資料時,還是沒有改變前的資料.

   原因是:.getResourceAsStream是通過快取中獲取的.

   解決辦法:能過真實路徑獲取TaskController.class.getResource("/config.properties").getPath();

操作properties檔案工具類:

package com.lanyuan.video.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Map.Entry;
import com.lanyuan.video.task.TaskController;

public class PropertiesUtils {
	/**
	 * 獲取屬性檔案的資料 根據key獲取值
	 * @param fileName 檔名 (注意:載入的是src下的檔案,如果在某個包下.請把包名加上)
	 * @param key
	 * @return
	 */
	public static String findPropertiesKey(String key) {
		
		try {
			Properties prop = getProperties();
			return prop.getProperty(key);
		} catch (Exception e) {
			return "";
		}
		
	}

	public static void main(String[] args) {
		Properties prop = new Properties();
		InputStream in = TaskController.class
				.getResourceAsStream("/config.properties");
		try {
			prop.load(in);
			Iterator<Entry<Object, Object>> itr = prop.entrySet().iterator();
			while (itr.hasNext()) {
				Entry<Object, Object> e = (Entry<Object, Object>) itr.next();
				System.err.println((e.getKey().toString() + "" + e.getValue()
						.toString()));
			}
		} catch (Exception e) {
			
		}
	}

	/**
	 * 返回 Properties
	 * @param fileName 檔名 (注意:載入的是src下的檔案,如果在某個包下.請把包名加上)
	 * @param 
	 * @return
	 */
	public static Properties getProperties(){
		Properties prop = new Properties();
		String savePath = TaskController.class.getResource("/config.properties").getPath();
		//以下方法讀取屬性檔案會快取問題
//		InputStream in = TaskController.class
//				.getResourceAsStream("/config.properties");
		try {
			InputStream in =new BufferedInputStream(new FileInputStream(savePath));  
			prop.load(in);
		} catch (Exception e) {
			return null;
		}
		return prop;
	}
	/**
	 * 寫入properties資訊
	 * 
	 * @param key
	 *            名稱
	 * @param value
	 *            值
	 */
	public static void modifyProperties(String key, String value) {
		try {
			// 從輸入流中讀取屬性列表(鍵和元素對)
			Properties prop = getProperties();
			prop.setProperty(key, value);
			String path = TaskController.class.getResource("/config.properties").getPath();
			FileOutputStream outputFile = new FileOutputStream(path);
			prop.store(outputFile, "modify");
			outputFile.close();
			outputFile.flush();
		} catch (Exception e) {
		}
	}
}