Java Properties類使用基礎
Properties類繼承自HashTable,通常和io流結合使用。它最突出的特點是將key/value作為配置屬性寫入到設定檔中以實現配置持久化,或從設定檔中讀取這些屬性。它的這些設定檔的規範尾碼名為".properties"。表示了一個持久的屬性集。
需要注意幾點:
- 無論是key還是value,都必須是String資料類型。
- 雖然繼承自HashTable,但它卻沒有使用泛型。
- 雖然可以使用HashTable的put方法,但不建議使用它,而是應該使用setProperty()方法。
- 多個線程可以共用單個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(); }}