Java Properties類使用基礎

來源:互聯網
上載者:User

Java Properties類使用基礎

Properties類繼承自HashTable,通常和io流結合使用。它最突出的特點是將key/value作為配置屬性寫入到設定檔中以實現配置持久化,或從設定檔中讀取這些屬性。它的這些設定檔的規範尾碼名為".properties"。表示了一個持久的屬性集。

需要注意幾點:

  1. 無論是key還是value,都必須是String資料類型。
  2. 雖然繼承自HashTable,但它卻沒有使用泛型。
  3. 雖然可以使用HashTable的put方法,但不建議使用它,而是應該使用setProperty()方法。
  4. 多個線程可以共用單個Properties對象而無需進行外部同步。即線程同步。

如果想將Properties集合中的屬性集寫入到設定檔中,使用store()方法;如果想從".properties"設定檔中讀取屬性,可以使用load()方法。

以下是Properties類的常用方法:

  • setProperty(String k,String v):調用hashtable的put方法,向properties集合中添加key/value,傳回值為key對應的舊值,如沒有舊值則返回Null。注意k和v都是String類型。
  • getProperty(String k):擷取properties集合中key對應的value。
  • store(OutputStream o,String comment):將properties屬性集合寫入到輸出資料流o中,注意,注釋comment必不可少。 - load(InputStream i):從.properties設定檔中按照位元組讀取其中的屬性。
  • load(Reader r):從.properties設定檔中按照字元讀取其中的屬性。
  • stringPropertyNames():返回properties集合中由key部分組成的Set集合。

以下是向properties集合中增、取、遍曆key/value以及和IO流結合使用的簡單樣本。

import java.util.*;import java.io.*;public class Prop {    public static void main(String[] args) throws IOException {        Properties prop = new Properties();        //向properties集合prop中儲存key/value        prop.setProperty("filename","a.avi");        prop.setProperty("size","5M");        //prop集合儲存key/value的格式        System.out.println(prop);        //從prop中取出單個key/value        prop.getProperty("filename");        //遍曆prop集合        Set<String> keys = prop.stringPropertyNames();        for (String key : keys) {            String value = prop.getProperty(key);            System.out.println(key+"="+value);        }        //properties集合和IO輸出資料流集合:將prop集合中的屬性集寫入到檔案中實現持久化        FileOutputStream fos = new FileOutputStream("d:/temp/my.properties");        prop.store(fos,"store test");        //properties集合和IO輸出資料流集合:從properties檔案中讀取屬性集到prop1集合中        //FileInputStream fis = new FileInputStream("d:/temp/my.properties");        FileReader fr = new FileReader("d:/temp/my.properties");        Properties prop1 = new Properties();  //Now it's a Null properties        prop1.load(fr);        System.out.println("new prop:"+prop1);        fos.close();        fr.close();    }}

聯繫我們

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