位置:org.springframework.util
�实现接口:org.springframework.util.PropertiesPersister
继承类:无
作用:为java.util.Properties提供各种实际操作的接入口

一、效果

输出conf.properties 文件中的所有properties键值对:

  1. @Test
  2. public void test1() throws Exception {
  3. DefaultPropertiesPersister dpp = new DefaultPropertiesPersister();
  4. Properties properties = new Properties();
  5. InputStream inputStream = new FileInputStream(new File("conf.properties"));
  6. dpp.load(properties,inputStream);
  7. Enumeration<?> enumeration = properties.propertyNames();
  8. while(enumeration.hasMoreElements()) {
  9. String strKey = (String) enumeration.nextElement();
  10. String strValue = properties.getProperty(strKey);
  11. System.out.println(strKey + "=" + strValue);
  12. }
  13. }

二、API

  1. // props:要存储的Properties对象
  2. public void load(Properties props, InputStream is) throws IOException {
  3. props.load(is);
  4. }
  5. public void load(Properties props, Reader reader) throws IOException {
  6. props.load(reader);
  7. }
  8. // header:属性列表的描述
  9. public void store(Properties props, OutputStream os, String header) throws IOException {
  10. props.store(os, header);
  11. }
  12. public void store(Properties props, Writer writer, String header) throws IOException {
  13. props.store(writer, header);
  14. }
  15. public void loadFromXml(Properties props, InputStream is) throws IOException {
  16. props.loadFromXML(is);
  17. }
  18. public void storeToXml(Properties props, OutputStream os, String header) throws IOException {
  19. props.storeToXML(os, header);
  20. }
  21. // 可设定编码encoding
  22. public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException {
  23. props.storeToXML(os, header, encoding);
  24. }

三、总结

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类的操作