zoukankan      html  css  js  c++  java
  • Properties的读取和写入

    Properties的读取和写入

    Properties是HashTable下的一个持久的属性集,没有泛型,key-value都是String类型。由于能与IO流结合使用,所以能方便地操作属性文件或者xml文件。

    一.properties读取配置文件,并输出到控制台:

    1 Properties properties = new Properties();
    2 FileReader fr = new FileReader("ltn.properties");
    3 properties.load(fr);
    4 fr.close();
    5 //输出 
    6 properties.list(System.out);

    二.properties集合数据写入配置文件:

    Properties pro = new Properties();
    pro.setProperty("key1", "value1");
    pro.setProperty("key2", "value2");
    FileWriter fw = new FileWriter("ltn.properties");
    pro.store(fw, "key-value");    //key-value:对属性文件的描述
    fw.close();
    ltn.properties:
    #key-value
    #Mon Dec 16 23:16:18 CST 2013
    key2=value2
    key1=value1

    三.properties读取xml:

    loadFromXML将XML 文档所表示的所有属性加载到此属性表中,但xml文档中必须申明

     <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

    并且xml格式也必须满足dtd的要求。

    1.properties.xml如下:

    复制代码
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties version="1.0">
    <comment>Properties读取xml</comment>
    <entry key="username">xyy</entry>
    <entry key="pwd">123456</entry>
    </properties>
    复制代码

    2.读取xml:

    Properties properties = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    properties.loadFromXML(fis);
    fis.close();
    properties.list(System.out);

    3.输出:

    -- listing properties --
    pwd=123456
    username=xyy

    四.将properties集合数据写入xml文件:

    1.写入:

    Properties properties = new Properties();
    properties.setProperty("username", "xyy");
    properties.setProperty("pwd", "123456");
    FileOutputStream fos = new FileOutputStream("properties2.xml");
    properties.storeToXML(fos,"key-value");
    fos.close();

    2.生成xml:

    复制代码
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <comment>key-value</comment>
    <entry key="pwd">123456</entry>
    <entry key="username">xyy</entry>
    </properties>
    复制代码
     
     
     
    标签: java
  • 相关阅读:
    AgilePoint模型驱动BPM(业务流程管理)介绍
    WF从入门到精通(第五章):workflow跟踪 (转)
    昕友.亿达PM项目管理软件 结构草图
    C++之虚拟继承
    Using Batch Parameters
    Static 关键字 C and C++
    something about code coverage planning
    C++ 虚函数表
    C++ FAQ for me
    Drag and Drop in WPF
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3477714.html
Copyright © 2011-2022 走看看