最近遇到需要动态替换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 动态地替换多个键值对。该方法灵活且高效,适用于需要对配置文件进行动态修改的场景。