Java封装读取properties配置文件的工具类【杭州多测师_王sir】
package cn.duoceshi.springbootdemo.utils; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.*; @Slf4j public class PropertyUtils { public static Map<String, String> getAll(String filePath) { Map<String, String> propertyMap = new HashMap<String, String>(); File file = new File(filePath); if (!file.exists()) { log.error("配置文件不存在, 路径: " + filePath); return propertyMap; } Properties properties = new Properties(); try { InputStreamReader reader = new InputStreamReader(new FileInputStream(filePath),"UTF-8"); properties.load(new BufferedReader(reader)); Set<String> names = properties.stringPropertyNames(); if (null == names || names.size() == 0) return propertyMap; for (String name : names) { propertyMap.put(name, properties.getProperty(name)); } return propertyMap; } catch (Exception ex) { log.error("读取配置文件失败"); } return propertyMap; } public static Map<String, String> getAll(InputStream inputStream) { Map<String, String> propertyMap = new HashMap<String, String>(); Properties properties = new Properties(); try { properties.load(inputStream); Set<String> names = properties.stringPropertyNames(); if (null == names || names.size() == 0) return propertyMap; for (String name : names) { propertyMap.put(name, properties.getProperty(name)); } return propertyMap; } catch (Exception ex) { log.error("读取配置文件失败"); } return propertyMap; } public static void writeProperties(String filePath, Map<String, String> props) { Properties properties = new Properties(); FileOutputStream output = null; File file = new File(filePath); if (!file.exists()) { log.error("配置文件不存在, 路径: " + filePath); return; } try { output = new FileOutputStream(filePath); for (Map.Entry<String, String> entry : props.entrySet()){ properties.setProperty(entry.getKey(), entry.getValue()); } properties.store(output, new Date().toString());// 保存键值对到文件中 } catch (IOException io) { io.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static String get(String filePath, String key) { File file = new File(filePath); if (!file.exists()) { log.error("配置文件不存在, 路径: " + filePath); return null; } Properties properties = new Properties(); try { properties.load(new FileInputStream(filePath)); Set<String> names = properties.stringPropertyNames(); if (null == names || names.size() == 0) return null; for (String name : names) { if (name.trim().equals(name.trim())) return properties.getProperty(name); } return null; } catch (Exception ex) { log.error("读取配置文件失败"); return null; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2022-08-30 杭州市民卡面试题【杭州多测师】【杭州多测师_王sir】
2020-08-30 java编程语言中的多态【多测师_王sir】