Java代码操作properties配置文件(读取,新增/修改,删除)

 

项目中需要用到操作properties文件中的数据,记录一下

package com.bonc.savepic.save; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @Author clj * @SinceDate 2019/3/26 17:05 * @Description */ public class PropertiesUtil { /** * 获取Properties对象 * @return */ public static Properties getProperties(){ Properties properties = new Properties(); InputStream inputStream = null; try { //data.properties在resources目录下 inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("data.properties"); properties.load(inputStream); } catch (FileNotFoundException e) { System.out.println("data.properties文件未找到!"); } catch (IOException e) { System.out.println("出现IOException"); } finally { try { if (null != inputStream){ inputStream.close(); } } catch (IOException e) { System.out.println("data.properties文件流关闭出现异常"); } } return properties; } /** * 根据key查询value值 * @param key key * @return */ public static String getValue(String key){ Properties properties = getProperties(); String value = properties.getProperty(key); return value; } /** * 新增/修改数据 * @param key * @param value */ public static void setValue(String key, String value){ Properties properties = getProperties(); properties.setProperty(key, value); //此处获取的路径是target下classes //这里的path是项目文件的绝对路径 //先获取项目绝对路径:Thread.currentThread().getContextClassLoader().getResource("").getPath(); //然后在项目路径后面拼接"properties/sysConfig.properties"; // 原注释 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); path = path + "data.properties"; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(path); properties.store(fileOutputStream, "注释"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != fileOutputStream){ fileOutputStream.close(); } } catch (IOException e) { System.out.println("data.properties文件流关闭出现异常"); } } } /** * 删除和修改只有语句不同 * properties.remove(key); */ }

 转载


__EOF__

本文作者皮军旗
本文链接https://www.cnblogs.com/pijunqi/p/14688734.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   皮军旗  阅读(929)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示