ITeye博客

Properties类小结

dh189 · 2010-09-06 16:20 · java · 编程语言 · Markdown

目前有个任务,要用到java.util.Properties类及其拓展知识.在这里先把预备知识梳理一下,过几天再把commons configuration整理出来. 

一.Properties 简介 
java.util.Properties 继承自 java.util.Hashtable 
Properties 类表示一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串. 

二.基本方法 
2.1 如何从输入流中加载属性文件 
使用load(InputStream is)方法: 

Java代码 

  1. Properties properties = new Properties();
  2. InputStream is = new FileInputStream("conn.properties");
  3. properties.load(is);
  4. is.close();

2.2 如何读属性文件中的值 
使用getProperties(String key)方法: 

Java代码 

  1. String temp = properties.getProperties(String key);

<注>重载的方法getProperties(String key, String default)方法 将在查询不到值的情况下,返回default. 
即: 如果 null == properties.getProperties(String key); 
则有 default == properties.getProperties(String key, String default); 

2.3 如何获取属性文件中的所有的键 
使用propertyNames()方法,该方法返回是键的枚举. 

Java代码 

  1. Enumeration enumeration = properties.propertyNames();

2.4 如何修改属性文件中的值 
使用

Java代码 

  1. setProperties(String key, String value)

方法. 
<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值. 

2.5 如何存储属性文件到输出流 
使用store(OutputStream os, String description)方法: 

Java代码 

  1. Properties properties = new Properties();
  2. OutputStream os = new FileOutputStream("test.properties");
  3. String description = "store properties to test.properties";
  4. properties.store(os, description);
  5. os.close();

2.6 如何清空所有值 
使用

Java代码 

  1. clear()

方法. 
<注>该方法继承自 Hashtable 的clear()方法.清空哈希表. 

三.实例附件 
<注>实例中没有指明properties文件的绝对路径.那么默认是在项目根目录下的. 
当生成新文件时,使用F5刷新就能看见新文件产生了.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。