天天看點

properties的讀取與寫入

在java.util 包下面有一個類

properties,該類主要用于讀取以項目的配置檔案(以.properties結尾的檔案和xml檔案)。 

  properties的構造函數有兩個,一個不帶參數,一個使用一個properties對象作為參數。

  使用properties讀取.properties檔案

  test.properties檔案如下:

  #測試環境配置:平台路徑配置

  jstrd_home=d:/tms2006/webapp/tms2006/web-inf/

  dbport = localhost

  databasename = mydb

  dbusername = root

  dbpassword = root

  # 以下為資料庫表資訊

  dbtable = mytable

  # 以下為伺服器資訊

  ip = 192.168.0.9

  讀取test.properties的方法如下:

  impor java.io.*;

  import java.util.*;

  public class readproperties {

      public static void main(string[] args) {

          file pfile = new

file("e:\\test.properties");    //

properties檔案放在e盤下(windows)

          fileinputstream

  pinstream=null;

         try {

         

   pinstream = new fileinputstream(pfile );

         } catch

(filenotfoundexception e) {

   e.printstacktrace(); //to change body of catch statement use

file | settings    

            

 |file templates.

         }

         properties p =

new properties();

    

        p .load(pinstream );

      //properties 對象已生成,包括檔案中的資料

         } catch

(ioexception e) {

        e.printstacktrace(); //to

change body of catch statement use file |

settings    

      

        |file

templates.

         }

         enumeration enu

= p.propertynames();     //取出所有的key

         //輸出--1

    p.list(system.out) ;

       //system.out可以改為其他的輸出流(包括可以輸出到檔案)

         //輸出--2

   

      while( enu

.hasmoreelements()){

    system.out.print("key="+enu.nextelement());

    system.out.print("value="+p.getproperty((string)enu

.nextelement()));

      }

  }

  讀取xml格式的配置檔案

  test.xml檔案ruxi

  <?xml version="1.0" encoding="utf-8"?>

  <!doctype properties system

"http://java.sun.com/dtd/properties.dtd">

  <properties>

  <entry key="koo">bar</entry>

  <entry key="fu">baz</entry>

  </properties>

  讀取xml的方法

  import java.io.ioexception;

  import java.io.file;

  import java.io.fileinputstream;

  import java.util.properties;

  public class test {

      public static void main(string[] args) {

         file pfile =

new file("e:\\test.xml");    // properties檔案放在e盤下(windows)

         fileinputstream

pinstream = null;

         pinstream = new

fileinputstream(pfile);

    p.loadfromxml(pinstream);

    p.list(system.out);

          }

catch (ioexception e) {

        e.printstacktrace();

         }

      }

  通過list 方法将properties寫入properties文

  import java.io.printstream;

    p.setproperty("id","dean");

    p.setproperty("password","123456");

         try{

        printstream fw = new

printstream(new file("e:\\test1.properties"));

        p.list(fw );

       } catch (ioexception e) {

  儲存為xml

printstream(new file("e:\\test1.xml"));

        p.storetoxml(fw,"test");