溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java如何實現(xiàn)properties文件動態(tài)修改并自動保存工具類

發(fā)布時間:2021-07-23 09:16:27 來源:億速云 閱讀:329 作者:小新 欄目:編程語言

這篇文章主要為大家展示了“Java如何實現(xiàn)properties文件動態(tài)修改并自動保存工具類”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“Java如何實現(xiàn)properties文件動態(tài)修改并自動保存工具類”這篇文章吧。

具體如下:

一、概述

利用commons-configuration讀取配置文件,并實現(xiàn)對配置文件的動態(tài)修改和自動保存。

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

二、示例:

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) {
    //執(zhí)行初始化 
    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);
  }
}

以上是“Java如何實現(xiàn)properties文件動態(tài)修改并自動保存工具類”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI