Java Properties类使用基础

栏目: Java · 发布时间: 8年前

内容简介: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();
    }
}

本文永久更新链接地址 http://www.linuxidc.com/Linux/2018-01/150102.htm


以上所述就是小编给大家介绍的《Java Properties类使用基础》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mastering Regular Expressions, Second Edition

Mastering Regular Expressions, Second Edition

Jeffrey E F Friedl / O'Reilly Media / 2002-07-15 / USD 39.95

Regular expressions are an extremely powerful tool for manipulating text and data. They have spread like wildfire in recent years, now offered as standard features in Perl, Java, VB.NET and C# (and an......一起来看看 《Mastering Regular Expressions, Second Edition》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具