使用java 处理 properties 熟悉文件是一件非常简单的事情。先贴上几句别人说的话先:
Properties类的重要方法
Properties 类存在于胞 Java.util 中,该类继承自 Hashtable
1. getProperty ( String key) , 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream) ,从输入流中读取属性列表(键和元素对)。通过对指定的文件进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments) ,以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear () ,清除所有装载的 键 - 值对。该方法在基类中提供。
package chenluozhi;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* properties 文档解析测试
* @author 陈罗志
* @date 2011-10-25
* @config.properties 放在 src/bin 目录下
*/
public class PropertiesTest {
public static Map actionMap = new HashMap();
public PropertiesTest() {
}
public void operateProperties() {
Properties prop = new Properties();
try {
prop.load(this.getClass().getResourceAsStream(
"/config.properties"));
System.out.println("根据key(login)随意找出一个对应的值:"+prop.getProperty("login"));
Enumeration<Object> e = prop.keys();
//枚举所有 key-value对
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + "=" + prop.getProperty(key));
//根据这一思想,我们可以把对应的类全部加载到 内存,使用 hashmap存放,哈哈。太强大了。
// String className = prop.getProperty(key);
// System.out.println("正加载:"+className);
// Class c = Class.forName(className);
// actionMap.put(key, c.newInstance());
}
OutputStream fos = new FileOutputStream(this.getClass().getResource("/config.properties").getPath());
//修改一个
prop.setProperty("modify", "modify-by meme");
//添加一个
prop.setProperty("add", "add-by me");
prop.store(fos,"this is header");
fos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static void main(String args[]) {
PropertiesTest p = new PropertiesTest();
p.operateProperties();
}
}