属性文件.properties --java学习笔记

属性文件

  • 都只能是键值对
  • 键不能重复
  • 文件后缀一般是.properties结尾的
  • 存储有关系的数据,做为系统的配置文件

Properties

  • 是一个Map集合(键值对集合),但是我们一般不会当集合使用
  • 核心作用:Properties是用来代表属性文件的,通过Properties可以读写属性文件里的内容

使用Properties读取属性文件里的键值对数据

代码演示:

package com.zeyu.properties;

import java.io.FileReader;
import java.io.FileWriter;
import java.util.Properties;
import java.util.Set;

public class PropertiesTest1 {
    public static void main(String[] args) throws Exception {
        //1、建立一个Properties的对象出来(键值对集合,空容器)
        Properties properties = new Properties();

        //2、开始加载属性文件中的键值对数据到Properties对象中去
        properties.load(new FileReader("properties-xml-log\\src\\users.properties"));
        System.out.println(properties);

        //3、根据键取值
        System.out.println(properties.getProperty("admin"));
        System.out.println(properties.getProperty("王马小吉"));

        //4、遍历全部的键和值
        //方法一
        Set<String> keys = properties.stringPropertyNames();
        for (String key : keys) {
            System.out.println(properties.getProperty(key));
        }

        //方法二
        properties.forEach((k, v) -> System.out.println(k + ":" + v));

        
        //查找某个值并修改对应value
        if (properties.containsKey("王马小吉")) {
            properties.setProperty("王马小吉","The world is WangmaXiaoji‘s");
            properties.store(new FileWriter("properties-xml-log\\src\\users.properties"),"change password");
        }
    }
}

users.properties内容:

运行结果:

使用Properties把键值对数据写出到属性文件里去

代码演示:

import java.io.FileWriter;
import java.util.Properties;

public class PropertiesTest2 {
    public static void main(String[] args) throws Exception {
        //1创建Properties对象出来,先用他存储一些键值对数据
        Properties properties = new Properties();
        properties.setProperty("小鸟游六花","763390");
        properties.setProperty("小飞马","666zgrsg");
        properties.setProperty("孙悟空","xtqjql123456");

        //2、把properties对象中的键值对数据存入到属性文件中去
        properties.store(new FileWriter("properties-xml-log\\src\\users2.properties"),"save user message");

    }
}

运行结果:

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A泽予

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值