本文實例講述了Java實現的properties文件動態修改并自動保存工具類。分享給大家供大家參考,具體如下:
一、概述
利用commons-configuration讀取配置文件,并實現對配置文件的動態修改和自動保存。
Apache Common-Configuration工具可以從
Properties文件,XML文件,JNDI,JDBC數據源,System Properties,Applet parameters,Servlet Parameters等讀取相應信息
使用步驟
前提,引入commons-configuration-1.6.jar這個JAR包,同時還必須映入commm-logging.jar,common-lang.jar和common-collection.jar
二、示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
public class Config { private static PropertiesConfiguration propConfig; private static final Config CONFIG = new Config(); /** * 自動保存 */ private static boolean autoSave = true ; private Config() { } public static Config getInstance(String propertiesFile) { //執行初始化 init(propertiesFile); return CONFIG; } /** * 初始化 * * @param propertiesFile * @see */ private static void init(String propertiesFile) { try { propConfig = new PropertiesConfiguration(propertiesFile); //自動重新加載 propConfig.setReloadingStrategy( new FileChangedReloadingStrategy()); //自動保存 propConfig.setAutoSave(autoSave); } catch (ConfigurationException e) { e.printStackTrace(); } } /** * 根據Key獲得對應的value * * @param key * @return * @see */ public Object getValue(String key) { return propConfig.getProperty(key); } /** * 設置屬性 * * @param key * @param value * @see */ public void setProperty(String key, String value) { propConfig.setProperty(key, value); } } |
附:相關jar包本站下載地址如下:
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/lovoo/article/details/51718418