Java中的Property类
Property是JAVA中的属性操作类,该类在java.util包中,它是HashTable的子类。
常用函数列表:
l Properties()
n 构造函数
l setProperty(String key, String value)
n 设置属性的key-value
l store(OutputStream out, String comments)
n 将properties以键值对的方式存储为文本文件
l storeToXML(OutputStream os, String comment)
n 将properties以键值对的方式存储为XML文件
l load(InputStream inStream)
n 从文本文件中加载为properties对象
l loadFromXML(InputStream in)
n 从XML文件中加载为properties对象
l getProperty(String key, String defaultValue)
n 根据key获取value值
下面是示例代码:
import java.io.*; import java.util.*;
class Hello { public static void main(String[] args) throws Exception { Properties p = new Properties(); p.setProperty("name","sheldon"); p.setProperty("age","99"); p.setProperty("address","重庆市铜梁区");
File file1 = new File("D:" + File.separator + "code" + File.separator + "person.properties"); File file2 = new File("D:" + File.separator + "code" + File.separator + "person.xml");
p.store(new FileOutputStream(file1),"person info in txt"); p.storeToXML(new FileOutputStream(file2),"person info in xml");
Properties newP1 = new Properties(); newP1.load(new FileInputStream(file1)); System.out.println(newP1.getProperty("name"));
Properties newP2 = new Properties(); newP2.loadFromXML(new FileInputStream(file2)); System.out.println(newP2.getProperty("address"));
} } |