import java.util.*;
import java.io.*;
/**
* refer to http://www-900.ibm.com/developerworks/cn/java/j-tiger02254/index_eng.shtml </br>
* or http://www-900.ibm.com/developerworks/cn/java/j-tiger02254/index.shtml
*/
public class loadproperties
{
public static void main(string[] args) throws exception {
properties prop = new properties();
//load properties from configuration file
system.out.println("from properties file:");
fileinputstream fis = new fileinputstream("sample.properties");
prop.load(fis);
prop.list(system.out);
system.out.println("/nthe foo property: " + prop.getproperty("foo"));
//load properties from xml property file(tiger new method)
system.out.println("from xml file:");
fis =new fileinputstream("sampleprops.xml");
/**
*<pre>the xml document must have the following doctype declaration:
*<!doctype properties system "http://java.sun.com/dtd/properties.dtd">
*the dtd file :
*<?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>
*</pre>
*/
prop.loadfromxml(fis);
prop.list(system.out);
system.out.println("/nthe foo property: " + prop.getproperty("foo"));
//生成xml文件
system.out.println("produce a xml file");
prop = new properties();
prop.setproperty("one-two", "buckle my shoe");
prop.setproperty("three-four", "shut the door");
prop.setproperty("five-six", "pick up sticks");
prop.setproperty("seven-eight", "lay them straight");
prop.setproperty("nine-ten", "a big, fat hen");
fileoutputstream fos = new fileoutputstream("rhyme.xml");
/*
*default encoding is utf-8,
* if you need specify encoding,
* use storetoxml(outputstream os,string comment,string encoding) instead
*/
prop.storetoxml(fos, "rhyme");//prop.storetoxml(fos, "rhyme","gbk");
fos.close();//the specified stream remains open after storetoxml() returns,so must close obviously
/**
*生成的xml如下(dtd如上所述):
*<?xml version="1.0" encoding="utf-8"?>
*<!doctype properties system "http://java.sun.com/dtd/properties.dtd">
*<properties>
*<comment>rhyme</comment>
*<entry key="seven-eight">lay them straight</entry>
*<entry key="five-six">pick up sticks</entry>
*<entry key="nine-ten">a big, fat hen</entry>
*<entry key="three-four">shut the door</entry>
*<entry key="one-two">buckle my shoe</entry>
*</properties>
*/
}
}
闽公网安备 35060202000074号