java的读取和写入properties配置文件

本文主要讲述java读取和写入properties文件操作

一. 介绍Properties类

vip

 Properties用于读取和写入Xx.properties文件,获取k-v

二. Properties类的读取和写入

Properties类的读取:

复制代码
public class InoutProperties {
    public static void main(String[] args) {

    }

    @Test
    public void ReadProperties01() throws IOException {
        // 使用字符流读取【处理流】
        String filePath = "src\\mysql.properties";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String str = bufferedReader.readLine();
        HashMap<String, String> hashMap = new HashMap<>();
        while(str != null && !str.equals("")){
            String[] splits = str.split("=");
            hashMap.put(splits[0],splits[1]);
            str = bufferedReader.readLine();
        }
        // 遍历hashmap
        Set<Map.Entry<String, String>> entrySet = hashMap.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

    @Test
    public void ReadProperties02() throws IOException{
        // 使用Properties类读取文件
        String filePath = "src\\mysql.properties";
        // 1.创建对象
        Properties properties = new Properties();
        // 2.加载节点流
        properties.load(new FileReader(filePath));
        // 3.k-v结果显示到控制台
        properties.list(System.out);
        // 4.根据key获取value
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户: " + user + "密码: " + pwd);
    }
}
复制代码

Properties类的写入:

复制代码
public class OutInProperties {
    public static void main(String[] args) throws IOException {
        String filePath = "src\\mysql1.properties";
        Properties properties = new Properties();
        properties.setProperty("charset","utf-8");
        properties.setProperty("user","汤姆");
//        properties.store(new FileWriter(filePath),null); 【存储的是汉字】
        properties.store(new FileOutputStream(filePath),null); // 【存储的是汉字的unicode编码】

    }
}
复制代码

 

posted @   zwGitOne  阅读(839)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示