(集合类工具)Properties属性操作

Properties属性操作

在学习国际化程序的时候使用过(*.properties),那么这类文件存储结构是按照“key = value”的结构存储的,而这种形式与Map的存储结构很相似,但是区别在于.properties内容只能保存字符串,所以为了方便的描述属性的定义,在java.util包中提供有properties类型,此类是Hashtable的子类。

public class Properties
extends Hashtable<Object,​Object>

在继承Hashtable的时候为Hashtable中定义的泛型为Object,实际上Properties是不需要操作泛型的,因为它能操作的类型只能是String。

在Properties之中如果想要实现属性的操作可以采用如下的方法实现:

NO.方法类型描述
1 public Object setProperty​(String key, String value)普通设置属性
2public String getProperty​(String key)普通取得属性,key不存在返回null
3 public String getProperty​(String key, String defaultValue)普通取得属性,key不存在返回默认值
4public void store​(OutputStream out, String comments) throws IOException普通通过输出流输出属性内容
5public void load​(InputStream inStream) throws IOException普通通过输入流读取属性内容

范例:观察属性的设置和取得

import java.util.Properties;

public class PropertiesDemo {

    public static void main(String[] args) {

        Properties properties = new Properties();
        //设置只允许是字符串
        properties.setProperty("1","one");
        properties.setProperty("2","two");
        System.out.println(properties.getProperty("1"));
        System.out.println(properties.getProperty("2"));
        System.out.println(properties.getProperty("3"));    //key不存在返回null
        //找不到key时返回默认值
        System.out.println(properties.getProperty("3","three"));

    }

}

one
two
null
three

可以发现Properties里面可以像Map集合那样进行内容的设置与获取,但是唯一的是此类只能操作字符串,另外需要注意的是之所以会提供有Properties类是因为它可以通过输出流输出属性,也可以根据数据流读取属性。

范例:将属性保存在文件之中

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

public class PropertiesDemo {

    public static void main(String[] args) throws IOException {

        //创建一个输出流
        OutputStream out = new FileOutputStream("F:\\test.properties");

        Properties properties = new Properties();
        //设置只允许是字符串
        properties.setProperty("1","one");
        properties.setProperty("2","two");
        //输出
        properties.store(out,"comments,中文的注释看不见");


    }

}

此时已经生成了文件 ,注释中的中文是看不见的(需要插件支持)。

范例:读取test.properties文件(刚输出的那个)

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

public class PropertiesDemo {

    public static void main(String[] args) throws IOException {

        //创建一个输入流
        InputStream inputStream = new FileInputStream("F:\\test.properties");

        Properties properties = new Properties();
        properties.load(inputStream);   //读取文件内容
        System.out.println(properties.getProperty("1"));    //输出key为1的属性

    }

}

one

使用Properties类型最大的特点是可以进行资源内容的输入与输出的处理操作,在实际的开发之中,Properties往往用于读取配置资源的信息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值