使用Properties从文件获取属性

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>
   */
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值