Java中封裝設定檔(1)-使用Properties

來源:互聯網
上載者:User

  無論是有圖形化的選項配置對話方塊,或者是系統提供的註冊表,文本形式的本地設定檔依然是最牢靠、應用最廣泛的配置資訊儲存形式。配置資訊的一般模式就是一個配置項對應一個值,前者一般是個字串,後者可能是數字或者字串或者別的什麼。在傳統win32編程中有系統提供的api供我們解讀.ini檔案,後來也有操作註冊表的封裝好的api,在.net中更是有解讀XML形式.config檔案的現成方法。在Java中,對設定檔的使用進行封裝也是十分有意義的。

  封裝應該達到這樣的效果:應用只管從配置資訊進行按名讀取值、設定值、儲存等操作,而不需要關心具體以什麼檔案格式儲存、如何解析。檔案格式(純文字?XML?資料庫?)、IO方式(本地檔案?遠程檔案?控制台流?)在封裝類內部的變更,都不會影響應用對配置資訊的感知。

  從鍵名-值的對應關係以及檔案的存取,我們最容易想到的就是java.util.Properties對象,他是HashTable的子類,儲存的就是很多組鍵名-值的對應二原組,並提供快速的查詢和直接的從檔案讀取、儲存為檔案的方法。具體請參考相關文檔,我們直接看程式。

  首先自訂一個異常:


//ConfigurationException.java
package configuration;

public class ConfigurationException extends Exception{
  public ConfigurationException(){}
  public ConfigurationException(String msg){
    super(msg);
  }
}

  然後是我們的封裝類:


//Configuration.java
package configuration;
import java.io.*;
import java.util.*;
import configuration.*;

public class Configuration {
  private Properties config=new Properties();//記錄配置項
  private String fn=null;//記錄設定檔名

  //此構造方法用於建立設定檔
  public Configuration(){}

  //從指定檔案名稱讀入配置資訊
  public Configuration(String fileName)
      throws ConfigurationException {
    try {
      FileInputStream fin = new FileInputStream(fileName);
      config.load(fin); //載入檔案
      fin.close();
    }
    catch (IOException ex) {
      throw new ConfigurationException
          ("無法讀取指定的設定檔:"+fileName);
    }
    fn=fileName;
  }

  //指定配置項名稱,返回配置值
  public String getValue(String itemName){
    return config.getProperty(itemName);
  }

  //指定配置項名稱和預設值,返回配置值
  public String getValue(String itemName,
                         String defaultValue){
    return config.getProperty(itemName,defaultValue);
  }

  //設定配置項名稱及其值
  public void setValue(String itemName,String value){
    config.setProperty(itemName,value);
    return;
  }

  //儲存設定檔,指定檔案名稱和抬頭描述
  public void saveFile(String fileName,String description)
      throws ConfigurationException {
    try {
      FileOutputStream fout
          = new FileOutputStream(fileName);
      config.store(fout, description);//儲存檔案
      fout.close();
    }
    catch (IOException ex) {
      throw new ConfigurationException
          ("無法儲存指定的設定檔:"+fileName);
    }
  }

  //儲存設定檔,指定檔案名稱
  public void saveFile(String fileName)
      throws ConfigurationException {
    saveFile(fileName,"");
  }

  //儲存設定檔,採用原檔案名稱
  public void saveFile() throws ConfigurationException {
    if(fn.length()==0)
      throw new ConfigurationException
          ("需指定儲存的設定檔名");
    saveFile(fn);
  }
}

  從這個封裝類我們可以看到,執行個體化對象的時候我們可以指定一個檔案名稱使得從中讀取配置資訊,通過getValue方法取得屬性值,setValue方法設定屬性值,saveFile方法儲存檔案。然後我們具體來看看如何使用:


//SetConfig.java
import configuration.*;//包含這個包方能使用配置類
import java.io.*;

public class SetConfig {
  public static void main(String[] args) {
    try {
      Configuration config = new Configuration();
      //設定一些屬性值
      config.setValue("Max_Users_Count", "50");
      config.setValue("Max_OpenedFile_Count", "20");
      //儲存檔案
      config.saveFile("system.conf",
                      "Sytem Global Configuration");
    }
    catch (ConfigurationException ex) {
      //捕獲我們自訂的異常
      ex.printStackTrace();
    }
  }
}

  這段程式建立了一個配置,設定了兩個配置項:Max_Users_Count為50;Max_OpenedFile_Count為20。最後將這個配置儲存為system.conf檔案,並加入抬頭注釋"Sytem Global Configuration"。執行之後,在程式所在目錄下產生了一個system.conf檔案,我們用純文字編輯器開啟看看內容到底是什麼:


#Sytem Global Configuration
#Mon Aug 02 23:43:39 PDT 2004
Max_OpenedFile_Count=20
Max_Users_Count=50

  可以看到,第一行寫入了我們加入的抬頭注釋,第二行自動產生了一個時間,後面兩行用<配置項名稱>=<配置值>的形式記錄了配置資訊。下面我們來讀取這個設定檔:


//ReadConfig.java
import configuration.*;

public class ReadConfig {
  public static void main(String[] args) {
    try {
      //讀取指定檔案
      Configuration config
          = new Configuration("system.conf");
      //擷取特定值
      System.out.println
          (config.getValue("Max_Users_Count") +
          " users can be actived at the same time");
     //指定預設值
     System.out.println
          (config.getValue("Max_OpenedFile_Count", "10") +
          " files can be opened at the same time");
    }
    catch (ConfigurationException ex) {
      ex.printStackTrace();
    }
  }
}

  系統輸出了


50 users can be actived at the same time
20 files can be opened at the same time

這樣的資訊。表明我們成功讀取了配置資訊。

  這樣我們的封裝類可以勝任普通的配置資訊操作工作了。而且對於大多數的情況,這個類也足夠用了。這裡的代碼都是可複用的,大家可以直接拷貝到自己的工程中去。最後說明:這些屬性值當然可以自己在檔案裡面改動,而且這也是設定檔最常見的使用方式;#號開頭的都表示注釋,可以任意添加和刪除。

  任務完成了,但是還並不完美。採用Properties最大的方便就是有現成的查詢、設定、檔案存取方法,但是這樣的<配置項名稱>=<配置值>格式只是方便了在Java中的使用,考慮到系統將來的擴充性或者開發平台的遷移,都是欠妥的。下一次我們來試試利用DOM封裝XML格式的設定檔。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.