Java IO流之Properties类的详解

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

前言:

Properties类的基本介绍:
在这里插入图片描述

Properties类的常见方法如下:
在这里插入图片描述

一、使用Properties类来读取配置文件mysql.properties,具体代码如下:
mysql.properties配置文件中具体内容如下:
在这里插入图片描述

/**
 * 使用Properties类来读取mysql.properties文件
 */
public class Properties02 {
    public static void main(String[] args) throws IOException {
        //1.创建Properties对象
        Properties properties = new Properties();
        properties.load(new FileReader("src\\mysql.properties"));
        //3.把键值对 显示到控制台
        properties.list(System.out);
        System.out.println("--------------------")
        //根据key 获取对应的值
        String pwd = properties.getProperty("pwd");
        String user = properties.getProperty("user");
        System.out.println("用户名:" + user);
        System.out.println("密码:" + pwd);
    }
}

结果如下:

-- listing properties --
user=root
pwd=123456
ip=192.168.100.100
--------------------
用户名:root
密码:123456

二、使用Properties类 创建配置文件,修改配置文件内容,具体代码如下:

/**
 * 使用Properties类 创建配置文件,修改配置文件内容
 */
public class Properties03 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        //创建
        //1.如果该文件没有key,就是创建
        //2.如果改文件有key,就是修改
        /*
           Properties父类就是Hashtable,底层就是Hashtable 核心方法

            public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;//如果key存在,就替换
                return old;
            }
        }

        addEntry(hash, key, value, index); //如果是新key,就添加
        return null;
    }
         */
        properties.setProperty("charset", "utf8");
        properties.setProperty("user", "汤姆");
        properties.setProperty("pwd", "888");
        //store()方法的第二个参数,表示注释
        properties.store(new FileOutputStream("src\\mysql2.properties"), "hello");
        System.out.println("保存配置文件成功!");
    }
}

创建的配置文件如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

路宇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值