Sample屬性文件
sample.properties
foo=美女
fu=baz
加載屬性的Sample程序
[code]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"));
}
}
輸出結果如下:
-- listing properties --
fu=baz
foo=美女
The foo property: 美女[/code]
2. 從XML中加載屬性
下面是Properties DTD清單:
[code]<?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>[/code]
Sample XML屬性文件:sample.xml(符合上面的Properties DTD)
[code]<?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>[/code]
l <entry>標記指定具體一個屬性,由key屬性指定屬性名,而<entry>標記的內容指定屬性值
l <comment>標記可以用來指定註釋
從XML文件加載屬性的Sample程序
[code]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"));
}
}[/code]
輸出的結果是一樣的
可以看出方法很簡單:使用XML文件來保存屬性,使用loadFromXML()方法替代原來的load()方法來加載XML文件中屬性
3. 更新XML文件中的屬性值
Sample程序
[code]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"));
}
}[/code]
上面的例子加載了sample.xml中的屬性,更新了foo屬性的值,並新加了new-name屬性,調用storeToXML()方法保存到原文件中,並改變註釋內容爲Store Sample
程序執行後的sample.xml的內容如下:
[code]<?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>[/code]