Properties集合
概述
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。 一个属性列表可包含另一个属性列表作为它的“默认值,如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。
特点
Properties可以当做Map集合类使用
使用Properties当做属性集合使用,结合Properties特殊的方法
public Object setProperty(String key,String value)
public String getProperty(String key)
public Set stringPropertyNames()
Properties和IO流结合使用
public void load(Reader reader)
public void store(Writer writer,String comments)
public class OtherIODemo06 {
public static void main(String[] args) throws FileNotFoundException, IOException {
// 当做Map集合使用
Properties prop = new Properties();
prop.put("username", "xyr");
prop.put("password", "123456");
Set<Object> keys = prop.keySet();
for (Object obj : keys) {
System.out.println(obj);
}
// 当做Properties属性集合使用
prop.setProperty("username", "xyr");
prop.setProperty("password", "123456");
Set<String> keys = prop.stringPropertyNames();
for (String key : keys) {
String value = prop.getProperty(key);
System.out.println(key + "=" + value);
}
// Properties和IO流结合使用 load store
prop.load(new FileReader("xxx.properties"));
System.out.println(prop);
prop.setProperty("username", "xyr");
prop.setProperty("password", "789465451321348");
prop.store(new FileWriter("xxx2.txt"), "This is a comment");
}
}