zoukankan      html  css  js  c++  java
  • JAVA,读写properties文件

    代码如下:properties工具类

    package com.java.app01;
    
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Properties;
    import java.util.Set;
    
    public class PropertiesUtil {
        public static void main(String[] args) {
            Properties properties = readProperties("src/main/resources/account.properties");
            String pwd2 = properties.getProperty("pwd2");
            System.out.println(pwd2);
    
            HashMap<String, String> map = new HashMap<>();
            map.put("user1", "pwd1");
            map.put("user2", "pwd2");
            writeProperties(map,"src/main/resources/account1.properties");
    
        }
    
        // 读取properties文件
        public static Properties readProperties(String readFilePath) {
            Properties properties = new Properties();
            File file = new File(readFilePath);
            if (!file.exists()) {
                System.out.println("输入文件路径不存在");
                return null;
            }
            FileReader reader = null;
            try {
                reader = new FileReader(readFilePath);
                properties.load(reader);
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                return properties;
            }
    
        }
        // 写入properties文件,参数传文件路径和map数据
        public static void writeProperties(HashMap<String, String> mapData,String writeFilePath) {
            Properties properties = new Properties();
            File file = new File(writeFilePath);
            if (!file.exists()) {
                System.out.println("输入文件路径不存在");
                return;
            }
            try {
                Set<String> set = mapData.keySet();
                for (String key : set) {
                    String value = mapData.get(key);
                    properties.setProperty(key, value);
                }
                FileWriter writer = new FileWriter(writeFilePath);
                properties.store(writer, "data");
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }

  • 相关阅读:
    ES5特性Object.seal
    自定义右键菜单中bug记录
    ie9及以下不兼容event.target.dataset对象
    创建一个新数组并指定数组的长度
    vue组件的配置属性
    前端模板引擎和网络协议分类
    Python查询Mysql时返回字典结构的代码
    Python实现计算圆周率π的值到任意位的方法示例
    Python实现计算圆周率π的值到任意位的方法示例
    Python实现的计算马氏距离算法示例
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/15041515.html
Copyright © 2011-2022 走看看