• 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
  • 相关阅读:
    配置文件
    ajax
    网线颜色排序
    cs程序添加初始化加载
    后台设置gridview不换行
    js 经典正则判断 一个字符串是否包含另一个字符串
    窗体关闭事件
    oracle根据视图删除表
    (字符串)哈希
    (字符串)哈希
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3477714.html
Copyright © 2020-2023  润新知