Java Properties

1 Properties類的作用

    在我們平時寫程序的時候,有些參數是經常改變的,而這種改變不是我們預知的。比如說我們開發了一個操作數據庫的模塊,在開發的時候我們連接本地的數據庫那麼 IP ,端口號,數據庫名稱等信息並不是固定不變的,要使得這個操作數據的模塊具有通用性,那麼以上信息就不能寫死在程序裏。通常我們的做法是用配置文件來解決。 Java中有個比較重要的類Properties(Java.util.Properties),主要用於讀取Java的配置文件,在Java中,其配置文件常爲.properties文件,格式爲文本文件,文件的內容的格式是“鍵=值”的格式,文本註釋信息可以用"#"來註釋。

2 幾個重要方法

    繼承結構:

(1)void load(InputStream inStream)                         從輸入字節流中加載屬性列表(鍵值對)
(2)String getProperty(String key)                              根據key獲得對應的value
(3)Object setProperty(String key, String value)      調用 Hashtable 的 put方法,設置鍵值對。
(4)store(OutputStream out, String comments)        將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流。與 load 方法相反,該方法將鍵值對寫入到指定的文件中。
(5)void clear()                                                                調用父類Hashtable的clear方法,清除鍵值對列表
(6)Enumeration<?> propertyNames()                      Returns an enumeration of all the keys in this property list
(7)void list(PrintStream out)                                        Prints this property list out to the specified output stream
(8) boolean containsKey(Object key)                       父類的containsKey方法,判斷是否有指定的鍵

3 代碼實現

package pkgOne;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Properties;

public class LearnProperties {
	private static Properties properties=new Properties();
	
	public static void loadProperties() throws Exception{
		FileInputStream fileInput=new FileInputStream("e:/123.txt");
		BufferedInputStream bufferedInput=new BufferedInputStream(fileInput);
		
		properties.load(bufferedInput);
		
		bufferedInput.close();
		fileInput.close();
	}
	public static String getValue(String key) {
		if(properties.containsKey(key))
			return properties.getProperty(key);
		else {
			return "";
		}
	}
	public static void setValue(String key,String value) {
		properties.setProperty(key, value);
	}
	public static void saveProperties() throws Exception {
		FileOutputStream fileOutput=new FileOutputStream("e:/123.txt");
		BufferedOutputStream out=new BufferedOutputStream(fileOutput);
		properties.store(out, "存儲properties到指定文件");
		out.close();
		fileOutput.close();
	}
	public static void getAllProperties() {
		Enumeration<?> enumeration=properties.propertyNames();
		while (enumeration.hasMoreElements()) {
			String key = (String) enumeration.nextElement();
			String value=properties.getProperty(key);
			System.out.println("key:"+key+",value="+value);
		}
	}
	public static void printProperties() {
		properties.list(System.out);
	}
	public static void clearProperties() {
		properties.clear();
	}
	
	public static void main(String[] args) throws Exception{
		loadProperties();
		printProperties();
		System.out.println(getValue("name"));
		getAllProperties();
		setValue("sex", "man");
		getAllProperties();
		saveProperties();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章