Java 讀寫Properties配置文件

1.Properties類與Properties配置文件java

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

2.Properties中的主要方法對象

(1)load(InputStream inStream)blog

   這個方法能夠從.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,表示註釋信息;若是爲空則沒有註釋信息。get

  註釋信息後面是屬性文件的當前保存時間信息。string

(3)getProperty/setPropertyit

   這兩個方法是分別是獲取和設置屬性信息。

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);
        }
    } 
}
相關文章
相關標籤/搜索