Properties類

簡介:

Java中有個比較重要的類Properties(Java.util.Properties),主要用於讀取Java的配置文件,各類語言都有本身所支持的配置文件,配置文件中不少變量是常常改變的,這樣作也是爲了方便用戶,讓用戶可以脫離程序自己去修改相關的變量設置。code

主要的方法:

1. getProperty ( String key),用指定的鍵在此屬性列表中搜索屬性。也就是經過參數 key ,獲得 key 所對應的 value。資源

2. load ( InputStream inStream),從輸入流中讀取屬性列表(鍵和元素對)。經過對指定的文件(好比說上面的 test.properties 文件)進行裝載來獲取該文件中的全部鍵 - 值對。以供 getProperty ( String key) 來搜索。get

3. setProperty ( String key, String value) ,調用 Hashtable 的方法 put 。他經過調用基類的put方法來設置 鍵 - 值對。io

4. store ( OutputStream out, String comments),以適合使用 load 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的文件中去。table

5. clear (),清除全部裝載的 鍵 - 值對。該方法在基類中提供。class

讀取文件的方法:

InputStream in = getClass().getResourceAsStream("資源Name");test

或者變量

InputStream in = new BufferedInputStream(new FileInputStream(filepath));配置

例子:

配置文件file

文件名:Test.properties

name=wangwei
phone=18334702840

讀取

public class getProperties {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties pps = new Properties();
        //pps.load(new FileInputStream("Test.properties"));
        getProperties gP = new getProperties();
        String FileName = "Test.properties";
        InputStream is=gP.getClass().getResourceAsStream(FileName);
        pps.load(is);
        Enumeration enum1 = pps.propertyNames();//獲得配置文件的名字
        while(enum1.hasMoreElements()) {
            String strKey = (String) enum1.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }
    }
}
相關文章
相關標籤/搜索