一.Properties類與Properties配置文件

 Properties類繼承自Hashtable類而且實現了Map接口,也是使用一種鍵值對的形式來保存屬性集。不過Properties有特殊的地方,就是它的鍵和值都是字符串類型。咱們要作的第一步就是要將文件讀取到Properties類對象中,因爲load有一個參數是InputStream,因此咱們能夠用 InputStream的子類FileInputStream將屬性文件讀取到Properties對象中,知道prop.properties的路徑,咱們就用FileInputStream(String name)構造函數:java

二.Properties中的主要方法

(1)load(InputStream inStream)xcode

    這個方法能夠從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。以下面的代碼:函數

Properties pro = new Properties();
FileInputStream in = new FileInputStream("a.properties");
//屬性文件流   
pro.load(in);
//將屬性文件流裝載到Properties對象中
in.close();

(2)store(OutputStream out, String comments)在保存屬性集合到文件以前,咱們還有一件事情就是如何修改和添加新的屬性到屬性集合,這裏使用了一個方法就是setProperty(String key, String value),這個方法就是當屬性集合中存在指定的key時,就修改這個key的值,若是不存在,就新建一個key,一樣是經過鍵值關係保存的,但值得注意的是,Properties類繼承自Hashtable,因此也能夠用Hashtable的put和putAll方法保存,但強烈反對使用這兩個方法,由於它們容許調用方插入其鍵或值不是 Strings 的項。相反,應該使用 setProperty 方法。若是在「有危險」的 Properties 對象(即包含非 String 的鍵或值)上調用 store 或 save 方法,則該調用將失敗。那好,下面咱們就來看看修改、添加和保存屬性的程序:this

    這個方法將Properties類對象的屬性列表保存到輸出流中。以下面的代碼:spa

//修改baseFilePath的屬性值 
prop.setProperty("baseFilePath", "Boxcode"); 
//添加一個新的屬性studio 
prop.setProperty("studio", "Boxcode Studio"); 
//文件輸出流 
FileOutputStream fos = new FileOutputStream("prop.properties"); 
//將Properties集合保存到流中 
prop.store(fos, "Copyright (c) Boxcode Studio"); 
fos.close();//關閉流

 若是comments不爲空,保存後的屬性文件第一行會是#comments,表示註釋信息;若是爲空則沒有註釋信息。code

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

(3)getProperty/setProperty繼承

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

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);

        }

    } 

}

this.getClass().getResource("/").getPath().substring(1)+"system.properties";

--以上獲取運行環境可執行文件的路徑

相關文章
相關標籤/搜索