在做項目的時候有些數據不一定需要在數據庫管理,例如數據庫連接,定時任務等等的配置..有時候需要動態修改這些數據,但在修改完後,再次獲取時出現問題.
在項目中要修改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) {
}
}
}