首頁 > Java > java教程 > Java 讀寫Properties設定檔詳解

Java 讀寫Properties設定檔詳解

高洛峰
發布: 2017-01-12 10:29:09
原創
1687 人瀏覽過

Java 讀寫Properties設定檔

1.Properties類別與Properties設定檔

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

2.Properties中的主要方法

(1)load(InputStream inStream)

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

1

2

3

4

Properties pro = new Properties();

FileInputStream in = new FileInputStream("a.properties");

pro.load(in);

in.close();

登入後複製

   

(2)store(OutputStream out, String comments)

   這個方法將Properties類別物件的屬性清單儲存到輸出流中。如下面的程式碼:

1

2

3

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屬性列表,與生成屬性文件文件。代碼如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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

    }

  }

}

登入後複製

   

感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!

更多Java 讀寫Properties設定檔詳解相關文章請關注PHP中文網!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
java可以做為web的後端嗎?
來自於 1970-01-01 08:00:00
0
0
0
安裝JAVA
來自於 1970-01-01 08:00:00
0
0
0
無法安裝java
來自於 1970-01-01 08:00:00
0
0
0
求救:JAVA加密的資料PHP解密
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板