Properties的读取和写入
Properties是HashTable下的一个持久的属性集,没有泛型,key-value都是String类型。由于能与IO流结合使用,所以能方便地操作属性文件或者xml文件。
一.properties读取配置文件,并输出到控制台:
1 Properties properties = new Properties(); 2 FileReader fr = new FileReader("ltn.properties"); 3 properties.load(fr); 4 fr.close(); 5 //输出 6 properties.list(System.out);
二.将properties集合数据写入配置文件:
Properties pro = new Properties(); pro.setProperty("key1", "value1"); pro.setProperty("key2", "value2"); FileWriter fw = new FileWriter("ltn.properties"); pro.store(fw, "key-value"); //key-value:对属性文件的描述 fw.close();
ltn.properties: #key-value #Mon Dec 16 23:16:18 CST 2013 key2=value2 key1=value1
三.properties读取xml:
loadFromXML将XML 文档所表示的所有属性加载到此属性表中,但xml文档中必须申明
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
并且xml格式也必须满足dtd的要求。
1.properties.xml如下:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties version="1.0"> <comment>Properties读取xml</comment> <entry key="username">xyy</entry> <entry key="pwd">123456</entry> </properties>
2.读取xml:
Properties properties = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); properties.loadFromXML(fis); fis.close(); properties.list(System.out);
3.输出:
-- listing properties --
pwd=123456
username=xyy
四.将properties集合数据写入xml文件:
1.写入:
Properties properties = new Properties(); properties.setProperty("username", "xyy"); properties.setProperty("pwd", "123456"); FileOutputStream fos = new FileOutputStream("properties2.xml"); properties.storeToXML(fos,"key-value"); fos.close();
2.生成xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>key-value</comment> <entry key="pwd">123456</entry> <entry key="username">xyy</entry> </properties>