Java 修改 Properties 文件的完整指南
在 Java 中修改 properties 文件通常涉及读取、修改和重新写入文件的过程,以下是几种实现方法:

(图片来源网络,侵删)
使用 Properties 类(适用于内存修改)
import java.io.*;
import java.util.Properties;
public class ModifyProperties {
public static void main(String[] args) {
String filePath = "config.properties";
// 1. 加载现有属性文件
Properties prop = new Properties();
try (InputStream input = new FileInputStream(filePath)) {
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
// 2. 修改属性值
prop.setProperty("database.url", "jdbc:mysql://newhost:3306/mydb");
prop.setProperty("timeout", "60");
// 3. 保存回文件
try (OutputStream output = new FileOutputStream(filePath)) {
prop.store(output, "Updated configuration");
} catch (IOException io) {
io.printStackTrace();
}
}
}
使用 Files 类(Java 7+,更现代的方式)
import java.io.*;
import java.nio.file.*;
import java.util.Properties;
public class ModifyPropertiesWithFiles {
public static void main(String[] args) throws IOException {
Path path = Paths.get("config.properties");
// 读取文件内容
Properties prop = new Properties();
try (InputStream input = Files.newInputStream(path)) {
prop.load(input);
}
// 修改属性
prop.setProperty("new.property", "new.value");
// 写回文件
try (OutputStream output = Files.newOutputStream(path)) {
prop.store(output, "Modified by Java");
}
}
}
处理中文编码问题
properties 文件包含中文,需要指定编码:
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public class ModifyPropertiesWithEncoding {
public static void main(String[] args) throws IOException {
String filePath = "config.properties";
Properties prop = new Properties();
// 读取文件(指定UTF-8编码)
try (Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8)) {
prop.load(reader);
}
// 修改属性
prop.setProperty("chinese.name", "张三");
// 写回文件(指定UTF-8编码)
try (Writer writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) {
prop.store(writer, "Updated with Chinese support");
}
}
}
注意事项
- 文件锁定:在多线程环境中,确保文件操作是线程安全的
- 备份:修改前最好备份原文件
- 注释处理:Properties 类会保留注释,但修改后注释位置可能会变化
- 路径问题:确保使用正确的文件路径(绝对路径或相对路径)
替代方案:使用第三方库
对于更复杂的 properties 文件操作,可以考虑使用 Apache Commons Configuration:
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
public class ModifyWithCommons {
public static void main(String[] args) throws Exception {
Parameters params = new Parameters();
FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
.configure(params.properties().setFileName("config.properties"));
PropertiesConfiguration config = builder.getConfiguration();
config.setProperty("key", "new value");
builder.save();
}
}
方法提供了不同场景下修改 properties 文件的解决方案,您可以根据具体需求选择最适合的方式。
