TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
想必大家都用过*.properties文件,作为配置文件。但是,如果该文件写入了中文,待编译后内容就会成为乱码,使用native命令也好、使用ant执行编码转换也好,多少有点麻烦,与其如此,我们不如直接使用properties的xml格式。在JDK5中,properties文件的格式可以由XML构成.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>logoLocation</comment>
<entry
key="logoLocation"><![CDATA[/image/logo/]]></entry>
<entry
key="mail.host"><![CDATA[webmaster@zlex.org]]></entry>
<entry
key="site.name"><![CDATA[zlex中文网站]]></entry>
</properties>
[/code] 对应原有的properties文件
#logoLocation
logoLocation=/image/logo/
mail.host=webmaster@zlex.org
site.name=zlex中文网站
因为使用XML格式,不受系统编译影响,不存在中文问题.[/code] 这里给出了一个读取/书写XML格式properties文件的例子。
因为使用了XML,所以文件内容支持了CJKV(中文、日文、韩文、越南语)。可以直接书写、调用。
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Properties;
- public class PropertiesTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
-
-
- // 书写properties文件
- Properties properties = new Properties();
- properties.put("ONE", "1");
- properties.put("TWO", "2");
- properties.put("中文", "看看中文怎么样");
- properties.put("日本�", "日本�はどう?");
- properties.put("???", "???");
- properties.put("Th?o lu?n ti?ng Vi?t", "Th?o lu?n ti?ng Vi?t");
- OutputStream stream = null;
- http://www.loveapple.cn
- try {
- stream = new FileOutputStream("temp.xml");
- properties.storeToXML(stream, "Temporary Properties");
- }
- catch (IOException ex) {
- ex.printStackTrace();
- }finally{
- try{
- stream.close();
- }catch(Exception e){
- }
- }
- // 读取properties文件
- Properties properties2 = new Properties();
- InputStream is = null ;
- try{
- is = new FileInputStream("temp.xml");
- properties2.loadFromXML(is);
- System.out.println(properties2);
- }catch (IOException e) {
- e.printStackTrace();
- }finally{
- try{
- is.close();
- }catch (Exception e) {
- }
- }
- }
- }
复制代码
源码下载:http://file.javaxxz.com/2014/10/10/005842609.zip |
|