Properties类小结
目前有个任务,要用到java.util.Properties类及其拓展知识.在这里先把预备知识梳理一下,过几天再把commons configuration整理出来.
一.Properties 简介
java.util.Properties 继承自 java.util.Hashtable
Properties 类表示一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串.
二.基本方法
2.1 如何从输入流中加载属性文件
使用load(InputStream is)方法:
2.2 如何读属性文件中的值
使用getProperties(String key)方法:
<注>重载的方法getProperties(String key, String default)方法 将在查询不到值的情况下,返回default.
即: 如果 null == properties.getProperties(String key);
则有 default == properties.getProperties(String key, String default);
2.3 如何获取属性文件中的所有的键
使用propertyNames()方法,该方法返回是键的枚举.
2.4 如何修改属性文件中的值
使用
<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值.
2.5 如何存储属性文件到输出流
使用store(OutputStream os, String description)方法:
2.6 如何清空所有值
使用
<注>该方法继承自 Hashtable 的clear()方法.清空哈希表.
一.Properties 简介
java.util.Properties 继承自 java.util.Hashtable
Properties 类表示一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串.
二.基本方法
2.1 如何从输入流中加载属性文件
使用load(InputStream is)方法:
- Properties properties = new Properties();
- InputStream is = new FileInputStream("conn.properties");
- properties.load(is);
- is.close();
Properties properties = new Properties();
InputStream is = new FileInputStream("conn.properties");
properties.load(is);
is.close();
2.2 如何读属性文件中的值
使用getProperties(String key)方法:
- String temp = properties.getProperties(String key);
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()方法,该方法返回是键的枚举.
- Enumeration enumeration = properties.propertyNames();
Enumeration enumeration = properties.propertyNames();
2.4 如何修改属性文件中的值
使用
- setProperties(String key, String value)
setProperties(String key, String value)
方法.
<注>该方法调用的 Hashtable 的put方法.如果键存在,则修改值;如果键不存在,则添加值.
2.5 如何存储属性文件到输出流
使用store(OutputStream os, String description)方法:
- Properties properties = new Properties();
- OutputStream os = new FileOutputStream("test.properties");
- String description = "store properties to test.properties";
- properties.store(os, description);
- os.close();
Properties properties = new Properties();
OutputStream os = new FileOutputStream("test.properties");
String description = "store properties to test.properties";
properties.store(os, description);
os.close();
2.6 如何清空所有值
使用
- clear()
clear()
方法.
<注>该方法继承自 Hashtable 的clear()方法.清空哈希表.