编程那点事编程那点事

专注编程入门及提高
探究程序员职业规划之道!

Java的Properties集合

Map接口中还有一个实现类Hashtable,它和HashMap 十分相似,区别在于Hashtable是线程安全的。Hashtable存取元素时速度很慢,目前基本上被HashMap类所取代,但Hashtable类有一个子类Properties在实际应用中非常重要,Properties主要用来存储字符串类型的键和值,在实际开发中,经常使用Properties集合来存取应用的配置项。假设有一个文本编辑工具,要求默认背景色是红色,字体大小为14px,语言为中文,其配置项应该如下:

Backgroup-color=red
Font-size=14px
Language=chinese

在程序中可以使用Prorperties集合对这些配置项进行存取,接下来通过一个案例来学习,如例所示。

import java.util.Enumeration;
import java.util.Properties;
public class Example {
    public static void main(String[] args) {
        Properties p = new Properties(); // 创建Properties 对象
        p.setProperty("backgroup-color", "red");
        p.setProperty("Font-size", "14px");
        p.setProperty("Language", "chinese");
        Enumeration names = p.propertyNames(); // 获取Enumeration 对象所有键的枚举
        while (names.hasMoreElements()) { // 循环遍历所有的键
            String key = (String) names.nextElement();
            String value = p.getProperty(key); // 获取对应键的值
            System.out.println(key + "=" + value);
        }
    }
}

运行结果:

backgroup-color=red
Language=chinese
Font-size=14px

例的Properties类中,针对字符串的存取提供了两个专用的方法setProperty()和getProperty()。setProperty()方法用于将配置项的键和值添加到Properties集合当中。在第8行代码中通过调用Properties的propertyNames()方法得到一个包含所有键的Enumeration对象,然后在遍历所有的键时,通过调用getProperty()方法获得键所对应的值。

未经允许不得转载: 技术文章 » Java编程 » Java的Properties集合