位置:org.springframework.util
�实现接口:org.springframework.util.PropertiesPersister
继承类:无
作用:为java.util.Properties提供各种实际操作的接入口
一、效果
输出conf.properties
文件中的所有properties键值对:
@Test
public void test1() throws Exception {
DefaultPropertiesPersister dpp = new DefaultPropertiesPersister();
Properties properties = new Properties();
InputStream inputStream = new FileInputStream(new File("conf.properties"));
dpp.load(properties,inputStream);
Enumeration<?> enumeration = properties.propertyNames();
while(enumeration.hasMoreElements()) {
String strKey = (String) enumeration.nextElement();
String strValue = properties.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
二、API
// props:要存储的Properties对象
public void load(Properties props, InputStream is) throws IOException {
props.load(is);
}
public void load(Properties props, Reader reader) throws IOException {
props.load(reader);
}
// header:属性列表的描述
public void store(Properties props, OutputStream os, String header) throws IOException {
props.store(os, header);
}
public void store(Properties props, Writer writer, String header) throws IOException {
props.store(writer, header);
}
public void loadFromXml(Properties props, InputStream is) throws IOException {
props.loadFromXML(is);
}
public void storeToXml(Properties props, OutputStream os, String header) throws IOException {
props.storeToXML(os, header);
}
// 可设定编码encoding
public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException {
props.storeToXML(os, header, encoding);
}
三、总结
DefaultPropertiesPersister是PropertiesPersister接口的一个默认实现。
四、补充
各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。像Python支持的配置文件是.ini文件,同样,它也有自己读取配置文件的类ConfigParse,方便程序员或用户通过该类的方法来修改.ini配置文件。
在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用”#”来注释。
Properties类继承自Hashtable,它提供了几个主要的方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
参考资料: Java中Properties类的操作