Apache Commons Configuration簡介
使用Commons Configuration可以很好的管理我們的配置文件的讀寫,官網:http://commons.apache.org/configuration/
它支持對配置文件的讀取,保存,運行期加載,操作非常方便。下面簡單的一下代碼示例一下,具體的其他操作文檔可以去官方找到:
需要用到commons-lang,commons-collections,commons-logging,log4j
jar包
public class Test {public static void main(String[] args) throws ConfigurationException, InterruptedException { xmlLoadTest(); fileLoadTest(); saveTest(); runtimeReload(); } //xml文件 public static void xmlLoadTest() throws ConfigurationException{ String file = "test1.xml"; XMLConfiguration config = new XMLConfiguration(Test.class.getResource(file)); System.out.println(config.getString("conf.url")); System.out.println(config.getDouble("conf.money")); } //properties文件 private static void fileLoadTest() throws ConfigurationException { String file = "test2.properties"; PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file)); System.out.println(config.getString("url")); } //保存到文件 public static void saveTest() throws ConfigurationException{ String file = "test2.properties"; PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file)); //設置自動保存 或顯示調用 config.save(); config.setProperty("colors.background", "#000000"); config.setAutoSave(true); } //運行期參數修改加載 public static void runtimeReload() throws ConfigurationException, InterruptedException{ String file = "test2.properties"; PropertiesConfiguration config = new PropertiesConfiguration(Test.class.getResource(file)); config.setReloadingStrategy(new FileChangedReloadingStrategy()); System.out.println(config.getString("url")); Thread.sleep(10000);//在休眠期間,手動修改文件里面的url值后觀察日志情況 System.out.println(config.getString("url")); }
} </pre>Configuration 的參數可能來自下面的資源:
Properties files XML documents,Property list files (.plist),JNDI,JDBC Datasource,System properties, Applet parameters,Servlet parameters
本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!