读取/书写Java的XML格式properties文件

该博客演示了如何使用Java读写XML格式的properties文件。首先创建Properties对象并添加键值对,然后通过OutputStream将数据保存到XML文件。接着,从XML文件中加载Properties对象并打印内容,支持多种语言字符的存储和读取。
在JDK5中,properties文件的格式可以由XML构成,这里给出了一个读取/书写XML格式properties文件的例子。
因为使用了XML,所以文件内容支持了CJKV(中文、日文、韩文、越南语)。可以直接书写、调用。

例子代码:
  1. import java.io.FileInputStream;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.util.Properties;
  7. /**
  8.  * 
  9.  * 
  10.  * @author 郝春利
  11.  * @since 2008/09/11
  12.  * @version $Revision:$
  13.  */
  14. public class PropertiesTest {
  15.     /**
  16.      * @param args
  17.      */
  18.     public static void main(String[] args) {
  19.         
  20.         
  21.         // 书写properties文件
  22.         Properties properties = new Properties();
  23.         properties.put("ONE""1");
  24.         properties.put("TWO""2");
  25.         properties.put("中文""看看中文怎么样");
  26.         properties.put("日本語""日本語はどう?");
  27.         properties.put("한국어""한국어");
  28.         properties.put("Thảo luận tiếng Việt""Thảo luận tiếng Việt");
  29.         
  30.         OutputStream stream = null;
  31.         http://www.loveapple.cn
  32.         try {
  33.             stream = new FileOutputStream("temp.xml");
  34.             properties.storeToXML(stream, "Temporary Properties");
  35.         }
  36.         catch (IOException ex) {
  37.             ex.printStackTrace();
  38.         }finally{
  39.             try{
  40.                 stream.close();
  41.             }catch(Exception e){
  42.                 
  43.             }
  44.         }
  45.         // 读取properties文件
  46.         Properties properties2 = new Properties();
  47.         InputStream is = null ;
  48.         try{
  49.             is = new FileInputStream("temp.xml");
  50.             properties2.loadFromXML(is);
  51.             System.out.println(properties2);
  52.         }catch (IOException e) {
  53.             e.printStackTrace();
  54.         }finally{
  55.             try{
  56.                 is.close();
  57.             }catch (Exception e) {
  58.             }
  59.         }
  60.         
  61.     }
  62. }


输出结果:
  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
  3. <properties>
  4. <comment>Temporary Properties</comment>
  5. <entry key="TWO">2</entry>
  6. <entry key="ONE">1</entry>
  7. <entry key="한국어">한국어</entry>
  8. <entry key="Thảo luận tiếng Việt">Thảo luận tiếng Việt</entry>
  9. <entry key="日本語">日本語はどう?</entry>
  10. <entry key="中文">看看中文怎么样</entry>
  11. </properties>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值