Properties文件的XML格式(轉)


想必大家都用過*.properties文件,作為配置文件。但是,如果該文件寫入了中文,待編譯后內容就會成為亂碼,使用native命令也好、使用ant執行編碼轉換也好,多少有點麻煩,與其如此,我們不如直接使用properties的xml格式。

1
2
3
4
5
6
7
8
9
10
11
12
13
<? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
< properties >
     < comment >系統配置</ comment >
     < entry
         key = "logo.location" > <![CDATA[/image/logo/]]> </ entry >
     < entry
         key = "mail.host" > <![CDATA[webmaster@zlex.org]]> </ entry >
     < entry
         key = "site.name" > <![CDATA[zlex中文網站]]> </ entry >
     < entry
         key = "welcome" > <![CDATA[歡迎您,{0}!]]> </ entry >
</ properties >

對應原有的properties文件

1
2
3
4
5
#系統配置
logo.location= /image/logo/
mail.host=webmaster@zlex.org
site.name=zlex中文網站
welcome=歡迎您,{0}!

這里需要替換{0},可以使用MessageFormat,參考如下代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private FileInputStream fis;
 
     @Before
     public void init() {
         try {
             fis = new FileInputStream( new File( "config.xml" ));
         } catch (Exception e) {
             e.printStackTrace();
             fail(e.getMessage());
         }
     }
 
     @Test
     public void t() {
         Properties properties = new Properties();
         try {
             properties.loadFromXML(fis);
             System.err.println(MessageFormat.format(
                     (String) properties.get( "welcome" ), "snowolf" ));
         } catch (Exception e) {
             e.printStackTrace();
             fail(e.getMessage());
         }
     }

得到控制台輸出:

1
歡迎您,snowolf!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM