java基础(十五):Properties

Properties

  1. 继承了Hashtable,它是一个map映射
  2. Properties类表示了一个持久的属性集
  3. Properties可保存在流中或者从流中加载
  • 构造方法

    • Properties():创建一个无默认值的空属性列表
  • 特有方法:

    • String getProperty(String key): 用指定的键在此属性列表中搜索属性(只能是字符串类型)— 对应get()
    • Object setProperty(String key, String value): 调用 Hashtable 的方法 put(只能是字符串类型)— 对应put()
    • void store(OutputStream out, String comments): 将此 Properties 键值对写入字节输出流
    • void store(Writer writer, String comments): 将此 Properties 键值对写入字符输出流
    • void load(InputStream inStream): 从输入流中读取属性列表(键值对)
    • void load(Reader reader): 按简单的面向行的格式从输入字符流中读取属性列表(键值对)
    public class PropertiesDemo {
        public static void main(String[] args) throws IOException {
            // 创建Properties对象
            Properties properties = new Properties();
            // 添加元素 setProperty() key, value 均为字符串类型
            properties.setProperty("001","lili");
            properties.setProperty("002","Sam");
            properties.setProperty("003","Potter");
            System.out.println(properties);  // {001=lili, 002=Sam, 003=Potter}
            // 获取某个key对应的元素值
            String value = properties.getProperty("003");
            System.out.println(value);  // Potter
    
            // 将properties键值对输出到一个文件中
            FileOutputStream out = new FileOutputStream(".\\Day22\\pro.txt");
            // 将properties中的键值对持久化存储
            // 第二个参数comments用于添加文件的说明
            properties.store(out, null);
            // 关流
            out.close();
            
            Properties properties1 = new Properties();
            // 将文件中的内容读取到properties中
            FileInputStream in = new FileInputStream(".\\Day22\\pro.txt");
            // 调用加载方法
            properties1.load(in);
            // 关流
            in.close();
            // 输出properties中的数据
            System.out.println(properties1);  // {001=lili, 002=Sam, 003=Potter}
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值