服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

扫描关注微信公众号