在Java語言中,使用一種以.properties為副檔名的文字檔作為資源檔,該類型的檔案的內容格式為類似:
some_key=some_value #注釋描述
還有一種是使用xml檔案儲存項目的配置資訊,同樣可以使用Properties類解析。
xml設定檔格式:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>hello world</comment> <entry key="foo">bar</entry> <entry key="fu">baz</entry> </properties>
API講解 Properties 類表示了一個持久的屬性集。Properties 可儲存在流中或從流中載入。屬性列表中每個鍵及其對應值都是一個字串。
它提供了幾個主要的方法:
1. getProperty ( String key)
用指定的鍵在此屬性列表中搜尋屬性。也就是通過參數 key ,得到 key 所對應的 value。
2. load ( InputStream inStream)
從輸入資料流中讀取屬性列表(鍵和元素對)。通過對指定的檔案(比如說上面的 test.properties 檔案)進行裝載來擷取該檔案中的所有鍵 - 值對。以供 getProperty ( String key) 來搜尋。
3. setProperty ( String key, String value)
調用 Hashtable 的方法 put 。他通過調用基類的put方法來設定 鍵 - 值對。
4. store ( OutputStream out, String comments)
以適合使用 load 方法載入到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出資料流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的檔案中去。
5. clear ()
清除所有裝載的鍵 - 值對。該方法在基類中提供。
應用舉例
1、讀取.properties檔案指定key的value值程式碼範例如下(web項目):
public static String getProperties(String key) throws Exception {String value = "";InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("public.properties");Properties properties = new Properties();properties.load(inputStream);value = properties.getProperty(key);inputStream.close();return value;}
2、讀取xml配置跟讀取kv配置沒差別,就是把load換成xml對應的loadFromXML方法,代碼如下:
public class LoadSampleXML {public static void main(String args[]) throws Exception {Properties prop = new Properties();FileInputStream fis = new FileInputStream("sampleprops.xml");prop.loadFromXML(fis);prop.list(System.out);System.out.println("\nThe foo property: " + prop.getProperty("foo"));}}