(轉)Java 讀寫Properties設定檔

來源:互聯網
上載者:User

標籤:注釋   iter   []   roo   檔案的   name   nbsp   oid   try   

原文:http://www.cnblogs.com/xudong-bupt/p/3758136.html

 

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=rootpass=liukey=value

讀取a.properties屬性列表,與產生屬性檔案b.properties。代碼如下:

 
 1 import java.io.BufferedInputStream; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.InputStream;  5 import java.util.Iterator; 6 import java.util.Properties;  7  8 public class PropertyTest { 9     public static void main(String[] args) { 10         Properties prop = new Properties();     11         try{12             //讀取屬性檔案a.properties13             InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));14             prop.load(in);     ///載入屬性列表15             Iterator<String> it=prop.stringPropertyNames().iterator();16             while(it.hasNext()){17                 String key=it.next();18                 System.out.println(key+":"+prop.getProperty(key));19             }20             in.close();21             22             ///儲存屬性到b.properties檔案23             FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加開啟24             prop.setProperty("phone", "10086");25             prop.store(oFile, "The New properties file");26             oFile.close();27         }28         catch(Exception e){29             System.out.println(e);30         }31     } 32 }
 

(轉)Java 讀寫Properties設定檔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.