1.概述
- Properties 类表示一个持久的属性集,可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串;
- 因为 Properties 继承于 Hashtable,所以可对 Properties对象应用put和putAll方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项;相反,应该使用 setProperty 方法。
2.类的定义
public class Properties extends HashTable<Object, Object>{
public Properties(){} //构造方法
public void load(InputStream inStream) throws IOException{} //从输入流中读取属性列表(键和元素对)
public void store(OutputStream out, String comments) throws IOException{} //以适合使用load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流
public Object setProperty(String key, String value){} //调用 Hashtable 的方法 put
public String getProperty(String key){}
public String getProperty(String key, String defaultValue){} //用指定的键在属性列表中搜索属性。如果在属性列表中未找到该键,则接着递归检查默认属性列表及其默认值。如果未找到属性,则此方法返回默认值变量。
public Enumeration<?> propertyNames(){} //返回属性列表中所有键的枚举
public Set<String> stringPropertyNames(){} //返回此属性列表中的键集,其中该键及其对应值是字符串;返回的 set 不受 Properties 对象支持。对此 Properties 的改变不能在该 set 中反映出来,反之亦然
public void list(PrintStream out){} //将属性列表输出到指定的输出流
}
3.用例说明
Property.java
public class Property {
Properties pWrite = new Properties(); //构造properties对象
Properties pRead = new Properties();
/*写属性到properties对象*/
public void writeProperty(String key, String value){
pWrite.setProperty(key, value);
}
/*将properties保存到文件*/
public void saveProperty() throws FileNotFoundException, IOException{
pWrite.storeToXML(new FileOutputStream(new File("data.xml")), "第一次写入", "utf-8");
}
/*读取property属性*/
public String readProperty(String key) throws FileNotFoundException, IOException{
pRead.loadFromXML(new FileInputStream(new File("data.xml")));
return pRead.getProperty(key);
}
}
Test.java
import java.io.FileNotFoundException;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
Property instance = new Property();
instance.writeProperty("name", "panshan");
instance.writeProperty("sex", "man");
instance.writeProperty("age", "23");
instance.writeProperty("name", "panshan2");
instance.saveProperty();
String name = instance.readProperty("name");
String sex = instance.readProperty("sex");
String age = instance.readProperty("age");
String path = instance.readProperty("path");
instance.pRead.list(System.out);
}
}