Properties文件的XML格式

来源:互联网 发布:linux 软件版本 编辑:程序博客网 时间:2024/05/22 16:54
想必大家都用过*.properties文件,作为配置文件。但是,如果该文件写入了中文,待编译后内容就会成为乱码,使用native命令也好、使用ant执行编码转换也好,多少有点麻烦,与其如此,我们不如直接使用properties的xml格式。 
Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
  3. <properties>  
  4.     <comment>系统配置</comment>  
  5.     <entry  
  6.         key="logo.location"><![CDATA[/image/logo/]]></entry>  
  7.     <entry  
  8.         key="mail.host"><![CDATA[webmaster@zlex.org]]></entry>  
  9.     <entry  
  10.         key="site.name"><![CDATA[zlex中文网站]]></entry>  
  11.     <entry  
  12.         key="welcome"><![CDATA[欢迎您,{0}!]]></entry>  
  13. </properties>  

对应原有的properties文件 
Properties代码  收藏代码
  1. #系统配置  
  2. logo.location=/image/logo/  
  3. mail.host=webmaster@zlex.org  
  4. site.name=zlex中文网站  
  5. welcome=欢迎您,{0}!  

这里需要替换{0},可以使用MessageFormat,参考如下代码: 
Java代码  收藏代码
  1. private FileInputStream fis;  
  2.   
  3.     @Before  
  4.     public void init() {  
  5.         try {  
  6.             fis = new FileInputStream(new File("config.xml"));  
  7.         } catch (Exception e) {  
  8.             e.printStackTrace();  
  9.             fail(e.getMessage());  
  10.         }  
  11.     }  
  12.   
  13.     @Test  
  14.     public void t() {  
  15.         Properties properties = new Properties();  
  16.         try {  
  17.             properties.loadFromXML(fis);  
  18.             System.err.println(MessageFormat.format(  
  19.                     (String) properties.get("welcome"), "snowolf"));  
  20.         } catch (Exception e) {  
  21.             e.printStackTrace();  
  22.             fail(e.getMessage());  
  23.         }  
  24.     }  


得到控制台输出: 
引用
欢迎您,snowolf!

 

因为使用XML格式,不受系统编译影响,不存在中文问题!