Java Properties类使用基础


Properties类继承自HashTable,通常和io流结合使用。它最突出的特点是将key/value作为配置属性写入到配置文件中以实现配置持久化,或从配置文件中读取这些属性。它的这些配置文件的规范后缀名为".properties"。表示了一个持久的属性集。

需要注意几点:

  1. 无论是key还是value,都必须是String数据类型
  2. 虽然继承自HashTable,但它却没有使用泛型。
  3. 虽然可以使用HashTable的put方法,但不建议使用它,而是应该使用setProperty()方法。
  4. 多个线程可以共享单个Properties对象而无需进行外部同步。即线程同步。

如果想将Properties集合中的属性集写入到配置文件中,使用store()方法;如果想从".properties"配置文件中读取属性,可以使用load()方法。

以下是Properties类的常用方法:

  • setProperty(String k,String v):调用hashtable的put方法,向properties集合中添加key/value,返回值为key对应的旧值,如没有旧值则返回Null。注意k和v都是String类型。
  • getProperty(String k):获取properties集合中key对应的value。
  • store(OutputStream o,String comment):将properties属性集合写入到输出流o中,注意,注释comment必不可少。 - load(InputStream i):从.properties配置文件中按照字节读取其中的属性。
  • load(Reader r):从.properties配置文件中按照字符读取其中的属性。
  • stringPropertyNames():返回properties集合中由key部分组成的Set集合。

以下是向properties集合中增、取、遍历key/value以及和IO流结合使用的简单示例。

import java.util.*;
import java.io.*;

public class Prop {
    public static void main(String[] args) throws IOException {
        Properties prop = new Properties();

        //向properties集合prop中存储key/value
        prop.setProperty("filename","a.avi");
        prop.setProperty("size","5M");

        //prop集合存储key/value的格式
        System.out.println(prop);

        //从prop中取出单个key/value
        prop.getProperty("filename");

        //遍历prop集合
        Set<String> keys = prop.stringPropertyNames();
        for (String key : keys) {
            String value = prop.getProperty(key);
            System.out.println(key+"="+value);
        }

        //properties集合和IO输出流集合:将prop集合中的属性集写入到文件中实现持久化

        FileOutputStream fos = new FileOutputStream("d:/temp/my.properties");
        prop.store(fos,"store test");

        //properties集合和IO输出流集合:从properties文件中读取属性集到prop1集合中
        //FileInputStream fis = new FileInputStream("d:/temp/my.properties");
        FileReader fr = new FileReader("d:/temp/my.properties");
        Properties prop1 = new Properties();  //Now it's a Null properties
        prop1.load(fr);
        System.out.println("new prop:"+prop1);

        fos.close();
        fr.close();
    }
}

相关内容

    暂无相关文章