JDK1.5(代號Tiger)中更新了java.util.Properties類,提供了從XML文件中讀寫key-value對屬性的簡單方法:loadFromXML()和storeToXML()
1、基本加載屬性的方法
l Sample屬性文件:sample.properties
l 加載屬性的Sample程序
import java.io.FileInputStream;
import java.util.Properties;
public class LoadSampleProperties {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("props/sample.properties");
prop.load(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " + prop.getProperty("foo"));
}
}
l 輸出結果如下:
-- listing properties --
fu=baz
foo=bar
The foo property: bar
2、從XML中加載屬性
l 下面是Properties DTD清單:
<?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for properties -->
<!ELEMENT properties ( comment?, entry* ) >
<!ATTLIST properties version CDATA #FIXED "1.0">
<!ELEMENT comment (#PCDATA) >
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry key CDATA #REQUIRED>
l Sample XML屬性文件:sample.xml(符合上面的Properties DTD)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hello</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
</properties>
l <entry>標記指定具體一個屬性,由key屬性指定屬性名,而<entry>標記的內容指定屬性值
l <comment>標記可以用來指定注釋
l 從XML文件加載屬性的Sample程序
import java.io.FileInputStream;
import java.util.Properties;
public class LoadSampleXML {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("props/sample.xml");
prop.loadFromXML(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " + prop.getProperty("foo"));
}
}
l 輸出的結果是一樣的
l 可以看出方法很簡單:使用XML文件來保存屬性,使用loadFromXML()方法替代原來的load()方法來加載XML文件中屬性
3、更新XML文件中的屬性值
l Sample程序
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class UpdateSampleXml {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("props/sample.xml");
prop.loadFromXML(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " + prop.getProperty("foo"));
prop.setProperty("foo", "Hello World!");
prop.setProperty("new-name", "new-value");
FileOutputStream fos = new FileOutputStream("props/sample.xml");
prop.storeToXML(fos, "Store Sample");
fos.close();
fis = new FileInputStream("props/sample.xml");
prop.loadFromXML(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " + prop.getProperty("foo"));
}
}
l 上面的例子加載了sample.xml中的屬性,更新了foo屬性的值,并新加了new-name屬性,調用storeToXML()方法保存到原文件中,并改變注釋內容為Store Sample
l 程序執行后的sample.xml的內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Store Sample</comment>
<entry key="new-name">new-value</entry>
<entry key="fu">baz</entry>
<entry key="foo">Hello World!</entry>
</properties>