Properties类

  Properties继承于Hashtable,表示一个持久的属性集,属性列表中每个键及其对应值都是一个字符串。Properties类被许多Java类使用,例如在获取环境变量时,它就作为System.getProperties方法的返回值。
  Properties定义如下实例变量,这个变量持有一个Properties对象相关的默认属性列表:

Properties defaults;

  Properties类定义了两个构造方法,第一个构造方法没有默认值:

Properties();

第二个构造方法使用propDefault作为默认值:

Properties(Properties propDefault);

  除了从Hashtable中继承的方法,Properties还定义了以下方法:

  • String getProperty(String key):用指定的键在此属性列表中搜索属性。
  • String getProperty(String key, String defaultProperty):用指定的键在此属性列表中搜索属性。
  • void list(PrintStream streamOut):将属性列表输出到指定的输出流。
  • void list(PrintWriter streamOut):将属性列表输出到指定的输出流。
  • void load(InputStream streamIn) throws IOException:从输入流中读取属性列表(键和元素对)。
  • Enumeration propertyNames():按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
  • Object setProperty(String key, String value):调用Hashtable的方法put
  • void store(OutputStream streamOut, String description):以适合使用load(InputStream)方法加载到Properties表中的格式,将此Properties表中的属性列表(键和元素对)写入输出流。
import java.util.*;

public class PropDemo {
    public static void main(String args[]) {
        Properties capitals = new Properties();
        Set states;
        String str;

        capitals.put("Illinois", "Springfield");
        capitals.put("Missouri", "Jefferson City");
        capitals.put("Washington", "Olympia");
        capitals.put("California", "Sacramento");
        capitals.put("Indiana", "Indianapolis");

        /* Show all states and capitals in hashtable */
        states = capitals.keySet(); /* get set-view of keys */
        Iterator itr = states.iterator();

        while (itr.hasNext()) {
            str = (String) itr.next();
            System.out.println("The capital of " + str + " is " + capitals.getProperty(str) + ".");
        }

        System.out.println();

        /* look for state not in list -- specify default */
        str = capitals.getProperty("Florida", "Not Found");
        System.out.println("The capital of Florida is " + str + ".");
    }
}

执行结果:

The capital of Indiana is Indianapolis.
The capital of Illinois is Springfield.
The capital of Missouri is Jefferson City.
The capital of California is Sacramento.
The capital of Washington is Olympia.

The capital of Florida is Not Found.

  JavaIterator功能比较简单,并且只能单向移动:

  • 使用方法iterator要求容器返回一个Iterator。注意,iterator方法是java.lang.Iterable接口,被Collection继承。
  • 使用next获得序列中的下一个元素。第一次调用Iteratornext方法时,它返回序列的第一个元素。
  • 使用hasNext检查序列中是否还有元素。
  • 使用remove将迭代器新返回的元素删除。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值