java中Properties类的操作

1.概述

  • Properties 类表示一个持久的属性集,可保存在流中或从流中加载,属性列表中每个键及其对应值都是一个字符串;
  • 因为 Properties 继承于 Hashtable,所以可对 Properties对象应用put和putAll方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项;相反,应该使用 setProperty 方法。

2.类的定义

public class Properties extends HashTable<Object, Object>{
    public Properties(){}           //构造方法

    public void load(InputStream inStream) throws IOException{} //从输入流中读取属性列表(键和元素对)

    public void store(OutputStream out, String comments) throws IOException{}   //以适合使用load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流

    public Object setProperty(String key, String value){}       //调用 Hashtable 的方法 put

    public String getProperty(String key){}

    public String getProperty(String key, String defaultValue){}    //用指定的键在属性列表中搜索属性。如果在属性列表中未找到该键,则接着递归检查默认属性列表及其默认值。如果未找到属性,则此方法返回默认值变量。 

    public Enumeration<?> propertyNames(){} //返回属性列表中所有键的枚举

    public Set<String> stringPropertyNames(){}      //返回此属性列表中的键集,其中该键及其对应值是字符串;返回的 set 不受 Properties 对象支持。对此 Properties 的改变不能在该 set 中反映出来,反之亦然

    public void list(PrintStream out){}     //将属性列表输出到指定的输出流
}

3.用例说明

Property.java

public class Property {
    Properties pWrite = new Properties();               //构造properties对象
    Properties pRead = new Properties();

    /*写属性到properties对象*/
    public void writeProperty(String key, String value){
        pWrite.setProperty(key, value);
    }

    /*将properties保存到文件*/
    public void saveProperty() throws FileNotFoundException, IOException{
        pWrite.storeToXML(new FileOutputStream(new File("data.xml")), "第一次写入", "utf-8");
    }

    /*读取property属性*/
    public String readProperty(String key) throws FileNotFoundException, IOException{
        pRead.loadFromXML(new FileInputStream(new File("data.xml")));
        return pRead.getProperty(key);
    }
}

Test.java

import java.io.FileNotFoundException;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws FileNotFoundException, IOException {
        Property instance = new Property();

        instance.writeProperty("name", "panshan");
        instance.writeProperty("sex", "man");
        instance.writeProperty("age", "23");
        instance.writeProperty("name", "panshan2");
        instance.saveProperty();

        String name = instance.readProperty("name");
        String sex = instance.readProperty("sex");
        String age = instance.readProperty("age");
        String path = instance.readProperty("path");

        instance.pRead.list(System.out);
    }
}

这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值