Java中Properties的使用详解
java中有个比较重要的类properties(java.util.properties),主要用于读取java的配置文件,各种语言都有自己所支 持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。今天,我们就开始properties的使用。
java中properties的使用
properties的文档说明:
the properties class represents a persistent set of properties. the properties can be saved to a stream or loaded from a stream. each key and its corresponding value in the property list is a string.
properties类的描述:
public class properties extends hashtable<object,object>
测试的项目结构如下:
一、在huhx.properties文件中,我们为也方便,加入一条数据:
name=huhx
二、将huhx.properties文件加载读取,得到相应的属性
properties properties = new properties(); fileinputstream fis = new fileinputstream("huhx.properties"); properties.load(fis); system.out.println(properties.get("name"));
三、properties的list方法的使用
printstream printstream = system.out; properties.list(printstream);
list方法的具体代码:
public void list(printstream out) { out.println("-- listing properties --"); hashtable h = new hashtable(); enumerate(h); for (enumeration e = h.keys() ; e.hasmoreelements() ;) { string key = (string)e.nextelement(); string val = (string)h.get(key); if (val.length() > 40) { val = val.substring(0, 37) + "..."; } out.println(key + "=" + val); } }
四、properties的store方法的使用
outputstream outputstream = new fileoutputstream("huhx.txt"); properties.store(outputstream, "comments");
五、properties的storetoxml方法的使用
outputstream outputstream2 = new fileoutputstream("huhx.xml"); properties.storetoxml(outputstream2, "comments");
六、最终生成的文件如下:
huhx.txt:
#comments #thu may 19 19:19:36 cst 2016 name=huhx
huhx.xml:
<?xml version="1.0" encoding="utf-8" standalone="no"?> <!doctype properties system "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>comments</comment> <entry key="name">huhx</entry> </properties>
友情链接,propertiestest.java:
package com.huhx.linux; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.outputstream; import java.io.printstream; import java.util.properties; public class propertiestest { public static void main(string[] args) throws exception { // 一般properties的使用 properties properties = new properties(); fileinputstream fis = new fileinputstream("huhx.properties"); properties.load(fis); system.out.println(properties.get("name")); // 以下是测试的部分 printstream printstream = system.out; properties.list(printstream); outputstream outputstream = new fileoutputstream("huhx.txt"); properties.store(outputstream, "comments"); outputstream outputstream2 = new fileoutputstream("huhx.xml"); properties.storetoxml(outputstream2, "comments"); } }
以上所述是小编给大家介绍的java中properties的使用详解,希望对大家有所帮助