Java动态替换properties文件中键值方式
更新时间:2024年08月22日 17:10:43 作者:promise524
这篇文章主要介绍了Java动态替换properties文件中键值方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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 动态地替换多个键值对。
该方法灵活且高效,适用于需要对配置文件进行动态修改的场景。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java Fluent Mybatis实战之构建项目与代码生成篇下
Java中常用的ORM框架主要是mybatis, hibernate, JPA等框架。国内又以Mybatis用的多,基于mybatis上的增强框架,又有mybatis plus和TK mybatis等。今天我们介绍一个新的mybatis增强框架 fluent mybatis2021-10-10
Spring注解中@Configuration和@Component到底有啥区别
之前一直搞不清@Component和@Configuration这两个注解到底有啥区别,一直认为被这两修饰的类可以被Spring实例化嘛,最近终于弄明白了,这篇文章主要给大家介绍了关于Spring注解中@Configuration和@Component到底有啥区别的相关资料,需要的朋友可以参考下2023-04-04
SpringBoot部署到外部Tomcat无法注册到Nacos服务端的解决思路
这篇文章主要介绍了SpringBoot部署到外部Tomcat无法注册到Nacos服务端,本文给大家分享完美解决思路,结合实例代码给大家讲解的非常详细,需要的朋友可以参考下2023-03-03


最新评论