java中的properties檔案是一種配置檔案,主要用于表達配置資訊,檔案類型為*.properties,格式為文本檔案,檔案的内容是格式是"鍵=值"的格式,在properties
檔案中,可以用"#"來作注釋,properties檔案在java程式設計中用到的地方很多,操作很友善。
一、properties檔案
test.properties
------------------------------------------------------
#################################
# 工商報表應用icisreport的配置檔案#
# 日期:2006年11月21日 #
#
# 說明:業務系統topicis和報表系統icisreport是分離的
# 可分開部署到不同的伺服器上,也可以部署到同一個服務
# 器上;icisreprot作為獨立的web應用程式可以使用任何
# 的servlet容器或者j2ee伺服器部署并單獨運作,也可以
# 通過業務系統的接口調用作為業務系統的一個庫來應用.
# icisreport的ip
icisreport.server.ip=192.168.3.143
# icisreport的端口
icisreport.server.port=8080
# icisreport的上下文路徑
icisreport.contextpath=/icisreport
------------------------------------------------------
properties類的重要方法
properties 類存在于胞 java.util
中,該類繼承自 hashtable
1. getproperty ( string key) , 用指定的鍵在此屬性清單中搜尋屬性。也就是通過參數 key ,得到 key 所對應的 value。
2. load ( inputstream instream) ,從輸入流中讀取屬性清單(鍵和元素對)。通過對指定的檔案(比如說上面的 test.properties 檔案)進行裝載來擷取該文
件中的所有鍵 - 值對。以供 getproperty ( string key) 來搜尋。
3. setproperty ( string key, string value) ,調用 hashtable 的方法 put 。他通過調用基類的put方法來設定 鍵 - 值對。
4. store ( outputstream out, string comments) , 以适合使用 load 方法加載到 properties 表中的格式,将此 properties 表中的屬性清單(鍵和元素
對)寫入輸出流。與 load 方法相反,該方法将鍵 - 值對寫入到指定的檔案中去。
5. clear () ,清除所有裝載的 鍵 - 值對。該方法在基類中提供。
-------------------------------
二、操作properties檔案的java方法
讀屬性檔案
寫屬性檔案
總結:java的properties檔案需要放到classpath下面,這樣程式才能讀取到,有關classpath實際上就是java類或者庫的存放路徑,在java工程中,properties放到
class檔案一塊。在web應用中,最簡單的方法是放到web應用的web- inf\classes目錄下即可,也可以放在其他檔案夾下面,這時候需要在設定classpath環境變量的
時候,将這個檔案夾路徑加到 classpath變量中,這樣也也可以讀取到。在此,你需要對classpath有個深刻了解,classpath絕非系統中刻意設定的那個系統環境變
量,web-inf\classes其實也是,java工程的class檔案目錄也是。
發個例子大家自己看哈.