java动态替换properties文件中键值
最近遇到需要动态替换json文件中的值的需求,类比在 java 中读取 properties
文件,并根据传入的多个参数替换相应的 key 的属性值,基于使用 java.util.properties
类来实现。
实现
import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.map; import java.util.properties; public class propertiesmodifier { public static void main(string[] args) { // properties 文件路径 string propertiesfilepath = "xxxx_file.properties"; // 要修改的多个 key 及其新值 map<string, string> keyvalues = map.of( "key1", "newvalue1", "key2", "newvalue2" ); try { // 调用方法来修改 properties 文件中的多个 key 的值 modifyproperties(propertiesfilepath, keyvalues); } catch (ioexception e) { e.printstacktrace(); } } /** * 修改 properties 文件中指定的多个 key 的值 * * @param propertiesfilepath properties 文件路径 * @param keyvalues 要修改的 key 及其新值的 map * @throws ioexception 如果文件读取或写入时出现错误 */ public static void modifyproperties(string propertiesfilepath, map<string, string> keyvalues) throws ioexception { // 创建 properties 对象,用于处理 properties 文件 properties properties = new properties(); // 读取 properties 文件 try (inputstream input = new fileinputstream(propertiesfilepath)) { properties.load(input); } // 遍历要修改的 key 值,并更新到 properties 对象中 for (map.entry<string, string> entry : keyvalues.entryset()) { string key = entry.getkey(); string newvalue = entry.getvalue(); // 如果 key 存在,则替换其值 if (properties.containskey(key)) { properties.setproperty(key, newvalue); system.out.println("updated key: " + key + ", new value: " + newvalue); } else { system.out.println("key not found: " + key); } } // 将修改后的 properties 对象写回到文件中 try (outputstream output = new fileoutputstream(propertiesfilepath)) { properties.store(output, "updated properties file"); } // 输出修改后的 properties 内容 system.out.println("modified properties content: " + properties); } }
效果
- 修改前 properties 文件
database.url=jdbc:mysql://localhost:3306/mydb database.username=root database.password=secret app.name=myapplication
- 待修改数据
map<string, string> keyvalues = map.of( "database.username", "admin", "app.name", "icqq" );
- 修改后 properties 文件
database.url=jdbc:mysql://localhost:3306/mydb database.username=admin database.password=secret app.name=icqq
总结
通过 properties 类读取 properties 文件,并根据传入的 map 动态地替换多个键值对。
该方法灵活且高效,适用于需要对配置文件进行动态修改的场景。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论