IO流——Properties类

本次博客带领大家了解IO流中的Properties类,介绍它的常用方法和注意事项等等。

Properties类

  1. 专门用于读写配置文件的集合类,配置文件的格式:键 = 值。
  2. 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String。
  3. Properties的常用方法:
    • load :加载配置文件的键值对到Properties对象。
    • list :将数据显示到指定设备。
    • getProperty(key) :根据键获取值。
    • setProperty(key,value) :设置键值对到Properties对象。
    • store :将Properties中的键值对存储到配置文件,在idea 中,保存信息到配置文件,如果含有中文,会存储为unicode码。
  • 案例1:使用Properties类来读取mysql.properties 文件。
public class Properties02 {
    public static void main(String[] args) throws IOException {
        //使用Properties类来读取mysql.properties 文件。

        //1. 创建Properties 对象
        Properties properties = new Properties();
        //2. 加载指定配置文件
        properties.load(new FileReader("src\\com\\mysql.properties"));
        //3. 把K-V显示到控制台
        properties.list(System.out);
        //4. 根据key 获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名="+user);
        System.out.println("密码="+pwd);
    }
}
  • 案例2:使用Properties 类来创建 配置文件,修改配置文件内容。
public class Properties03 {
    public static void main(String[] args) throws IOException {
        //使用Properties 类来创建 配置文件,修改配置文件内容。

        Properties properties =new Properties();
        //创建
        //1. 如果该文件没有key,就是创建
        //2. 如果该文件有key,就是修改
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");
        properties.setProperty("pwd","888");

        //将k-v 存储文件中即可
        properties.store(new FileOutputStream("src\\com\\mysql2.properties"),null);
        System.out.println("保存成功!");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值