天天看點

Java 讀寫Properties配置檔案

1.Properties類與Properties配置檔案

  Properties類繼承自Hashtable類并且實作了Map接口,也是使用一種鍵值對的形式來儲存屬性集。不過Properties有特殊的地方,就是它的鍵和值都是字元串類型。

2.Properties中的主要方法

(1)load(InputStream inStream)

   這個方法可以從.properties屬性檔案對應的檔案輸入流中,加載屬性清單到Properties類對象。如下面的代碼:

Properties pro = new Properties();
FileInputStream in = new FileInputStream("a.properties");
pro.load(in);
in.close();      

(2)store(OutputStream out, String comments)

   這個方法将Properties類對象的屬性清單儲存到輸出流中。如下面的代碼:

FileOutputStream oFile = new FileOutputStream(file, "a.properties");
pro.store(oFile, "Comment");
oFile.close();      

  如果comments不為空,儲存後的屬性檔案第一行會是#comments,表示注釋資訊;如果為空則沒有注釋資訊。

  注釋資訊後面是屬性檔案的目前儲存時間資訊。

(3)getProperty/setProperty

   這兩個方法是分别是擷取和設定屬性資訊。

3.代碼執行個體

 屬性檔案a.properties如下:

name=root
pass=liu
key=value      

讀取a.properties屬性清單,與生成屬性檔案b.properties。代碼如下:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream; 
import java.util.Iterator;
import java.util.Properties; 

public class PropertyTest {
    public static void main(String[] args) { 
        Properties prop = new Properties();     
        try{
            //讀取屬性檔案a.properties
            InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
            prop.load(in);     ///加載屬性清單
            Iterator<String> it=prop.stringPropertyNames().iterator();
            while(it.hasNext()){
                String key=it.next();
                System.out.println(key+":"+prop.getProperty(key));
            }
            in.close();

            ///儲存屬性到b.properties檔案
            FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打開
            prop.setProperty("phone", "10086");
            prop.store(oFile, "The New properties file");
            oFile.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    } 
}      

歡迎關注微信公衆号:大資料從業者