Java常用類Properties簡單用法

Properties 是Java中非常常用的一個持久的屬性集類。Properties 可保存在流中或從流中加載,其屬性列表中每個鍵及其對應值都是一個字符串。

下面的例子對Properties 中常用的幾個方法做下示例說明

  • load(InputStream inStream) 
從輸入流中讀取屬性列表(鍵和元素對)
  • getProperty(String key)
用指定的鍵在此屬性列表中搜索屬性
  • getProperty(String key, String defaultValue)
用指定的鍵在屬性列表中搜索屬性。如果未找到屬性,則此方法返回默認值變量
  • propertyNames()
返回屬性列表中所有鍵的枚舉
  • setProperty(String key, String value)
    設置鍵值對
  • store(OutputStream out, String comments)
將屬性集文件更新
  • list(PrintStream out)
將屬性集寫入到流文件


我們的測試properties文件內容爲

jdbc.url=jdbc\:mysql\://localhost\:3306/sampledb
jdbc.username=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.password=root


整體代碼如下

package com.zhangqi.jdk;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class PropertiesTest {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		Properties prop = new Properties();
		
		// 從輸入流中讀取屬性列表(鍵和元素對)
		prop.load(new FileInputStream(new File("propTest.properties")));
		
		// 用指定的鍵在此屬性列表中搜索屬性
		String driver = prop.getProperty("jdbc.driver");
		System.out.println(driver);
		
		// 用指定的鍵在屬性列表中搜索屬性。如果未找到屬性,則此方法返回默認值變量
		String username = prop.getProperty("name", "admin");
		System.out.println(username);
		
		// 遍歷屬性值
		Set<String> propNames = prop.stringPropertyNames();
		Iterator<String> it = propNames.iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			String value = prop.getProperty(key);
			System.out.println(key + "=" + value);
		}
		
		// 調用 Hashtable 的方法 put。使用 getProperty 方法提供並行性。強制要求爲屬性的鍵和值使用字符串
		prop.setProperty("name", "lilei");
		String name = prop.getProperty("name");
		System.out.println(name);
		
		// 將屬性集文件更新
		prop.store(new FileOutputStream(new File("propTest.properties")), "zhangqi");
		
		// 創建新的流文件
		PrintStream fis = new PrintStream(new File("propNew.properties"));
		// 將屬性集寫入到流文件
		prop.list(fis);
	}
}


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