Java中导出Map为Properties文件需用Properties类的store(OutputStream)方法并指定UTF-8编码,键值须为String类型,null键跳过,value用String.valueOf()转换。

Java 中将 Map 导出为 Properties 文件,核心是使用 java.util.Properties 类(它本身继承自 Hashtable<Object, Object>),再通过其 store() 方法写入文件。关键在于:Map 的键和值必须是字符串类型,且需处理编码问题(避免中文乱码)。
确保 Map 的键值都是 String 类型
Properties 只接受 String 作为键和值。如果你的原始 Map 是 Map<String, Object> 或泛型不匹配,需先转换:
- 遍历原 Map,对每个 value 调用
String.valueOf()(安全,可处理 null) - 跳过 key 为 null 的条目(Properties 不允许 null key)
创建 Properties 并加载 Map 数据
不要直接用原始 Map 构造 Properties(会丢失类型安全),而是逐个 put:
Map<String, Object> sourceMap = new HashMap<>();
sourceMap.put("app.name", "MyApp");
sourceMap.put("db.url", "jdbc:mysql://localhost:3306/test");
sourceMap.put("debug", true);
<p>Properties props = new Properties();
for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
String key = entry.getKey();
String value = String.valueOf(entry.getValue());
if (key != null) {
props.setProperty(key, value);
}
}</p>用 OutputStream 写入文件并指定 UTF-8 编码
直接用 store(Writer) 时,Properties 默认按 ISO-8859-1 编码,中文会变乱码。推荐使用 store(OutputStream, String) 并传入 UTF-8 的 OutputStream:
立即学习“Java免费学习笔记(深入)”;
- 用
Files.newOutputStream(path)获取 UTF-8 安全的输出流 - 第二个参数是注释(可为 null 或空字符串)
Path path = Paths.get("config.properties");
try (OutputStream os = Files.newOutputStream(path)) {
props.store(os, "Generated by Java - " + new Date());
}
补充说明:如果必须用 Writer(如 FileWriter),要加头注释声明编码
若坚持用 store(Writer, ...),需手动在文件开头写入 #u0020 注释并确保 Writer 使用 UTF-8:
- 不推荐,容易遗漏或出错
- Properties 的
load(Reader)能识别\uXXXX转义,但普通中文仍需转义才能被 ISO-8859-1 正确读取 - 所以统一用 OutputStream + UTF-8 是最稳妥的做法


















