1. 程式人生 > >Java中Properties類的操作

Java中Properties類的操作

文件中 配置文件 所有 技術分享 set nbsp str 宋體 java

Java中有個比較重要的類Properties(Java.util.Properties),主要用於讀取Java的配置文件,就是像讀取數據庫賬號密碼一樣,其配置文件常為.properties文件,格式為文本文件,文件的內容的格式是“鍵=值”的格式,文本註釋信息可以用"#"來註釋。

Properties類繼承自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的話,完全可以在方法或者類裏面聲明一下代碼:

Properties p = new Properties();

下面列出幾個例子:

隨便新建一個配置文件(Test.properties)

name=JJ
Weight=4444
Height=3333
 1 public class getProperties {
 2     public static void main(String[] args) throws FileNotFoundException, IOException {
 3         Properties pps = new Properties();
 4         pps.load(new
FileInputStream("Test.properties")); 5 Enumeration enum1 = pps.propertyNames();//得到配置文件的名字 6 while(enum1.hasMoreElements()) { 7 String strKey = (String) enum1.nextElement(); 8 String strValue = pps.getProperty(strKey); 9 System.out.println(strKey + "=" + strValue); 10 } 11 } 12 }

但註意,在使用的時候,一定要在配置裏面配置相關代碼掃描此.properties結尾的文件。

歡迎加入java技術群進行討論,點我進群

Java中Properties類的操作