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

}

發佈了46 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章