Java Properties基礎知識總結

來源:互聯網
上載者:User
在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"));}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.