当前位置: 代码网 > it编程>编程语言>Java > Java IO流之Properties类的使用

Java IO流之Properties类的使用

2024年09月11日 Java 我要评论
前言properties类的基本介绍properties类的常见方法使用properties类来读取配置文件mysql.propertiesmysql.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)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com