Properties(配置資訊類)代表一個持久性的集合,它繼承自 Hashtable,以「鍵-值」方式存放資料,主要用於產生與讀取配置檔。本文示範其建立、寫入與讀取的完整流程。
import java.io.*;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class properties {
public static void main(String[] args) throws IOException {
createPropert();
readPropert();
}
// (一)建立配置資訊類
public static void createPropert() throws IOException {
Properties pt = new Properties();
pt.setProperty("初一", "1101");
pt.setProperty("小二", "1102");
pt.setProperty("張3", "1103");
pt.setProperty("lisi", "1104");
// 寫入中文時建議使用字元流
pt.store(new FileWriter("C:\\...\\配置流.properties"), "這是對檔案的描述資訊:");
}
// (二)讀取配置資訊
public static void readPropert() throws IOException {
Properties pt = new Properties();
pt.load(new FileReader("C:\\...\\配置流.properties"));
Set<Entry<Object, Object>> entrys = pt.entrySet();
for (Entry<Object, Object> entry : entrys) {
System.out.println("name:" + entry.getKey() + " id:" + entry.getValue());
}
}
}
建構方法:Properties() 無預設值;Properties(Properties defaults) 可指定預設值。
設定資訊:setProperty(key, value),鍵值皆為字串型別。
寫入資料:store(new FileWriter(...), "描述語")(寫中文建議用字元流)或 store(new FileOutputStream(...), "描述語")(位元組流)。
讀取資料:load(new FileReader(...)),以字元流讀取。
由於 Properties 本質是 Map,因此可直接用 foreach 遍歷 entrySet,輕鬆取得每一組鍵值對。