1. Properties类简介
Java.util.Properties类是Hashtable的一个子类,用于keys和values之间的映射。Properties类表示了一个持久的属性集,属性列表中每个键及其键值都是一个字符串。
2. 常用方法
(1)构造函数Properties():创建一个无默认值的空属性列表。
(2)String getProperty(String key):获取指定键key的键值,以字符串的形式返回。
(3)void load(InputString inStream):从输入流中读取属性列表。
(4)void setProperty(String key, String value):设置对象中key的键值。
(5)void store(OutputStream outStream, String comments):根据comments写入putStream。
目前本人接触到的comments有:
a. "store properties to file.properties": 将Properties对象写入文件, 向Properties对象中添加键和键值的映射,如果有重复键则用当前键值替换原键值。
b. "update 'keyname' value":用Properties对象内容更新文件中keyname的键值。
(6)void put(Object key, Object value): 向Properties对象中添加键和键值的映射,如果有重复键则用当前键值替换原键值。
3. 示例代码
以下代码仅仅是本人在学习Properties类过程中测试的一段代码,比较凌乱,但是能够说明Properties类的基本使用方法。
//PropertiesSample.java import java.util.*; import java.io.*; public class PropertiesSample { public static void main(String args[]) throws Exception { Properties prop = new Properties(); FileInputStream fis = new FileInputStream("sample1.properties"); prop.load(fis); prop.list(System.out); String foo = prop.getProperty("foo"); String fu = prop.getProperty("fu"); System.out.println("foo = " + foo); System.out.println("fu = " + fu); FileOutputStream fos = new FileOutputStream("sample1.properties"); prop.setProperty("foo", "fooValue55"); prop.setProperty("fu", "fuValue55"); prop.put("testkey1", "testvalue"); //prop.store(fos, "Update 'foo' value"); //prop.store(fos, "Update 'fu' value"); prop.store(fos, "store properties to sample1.properties"); FileInputStream fis1 = new FileInputStream("sample1.properties"); prop.load(fis1); prop.list(System.out); } }
//sample1.properties fu=abc11 foo=def11
运行结果:
-- listing properties --
//sample1.properties=
fu=abc11
foo=def11
foo = def11
fu = abc11
-- listing properties --
//sample1.properties=
testkey1=testvalue
fu=fuValue55
foo=fooValue55
sample1.properties文件内容:
#store properties to sample1.properties
#Thu Jul 18 22:24:49 CST 2013
testkey1=testvalue
fu=fuValue55
foo=fooValue55
注:部分内容获取于:
http://gimgen1026.iteye.com/blog/152023
http://lindows.iteye.com/blog/235844
http://www.blogjava.net/action/archive/2006/08/21/64804.html