Tiger系列一:从XML中加载属性
1、基本加载属性的方法
l Sample属性文件:sample.properties
foo=bar
fu=baz
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>