---
title: "Properties文件的XML格式"
author: "snowolf"
date: "2009-06-09T10:49:52Z"
tags: []
categories: ["编程语言"]
slug: "properties-xml"
draft: false
lastmod: "2011-02-10T13:52:01Z"
id: 404762
url: "https://snowolf.iteye.com/blog/404762"
---

想必大家都用过*.properties文件，作为配置文件。但是，如果该文件写入了中文，待编译后内容就会成为乱码，使用native命令也好、使用ant执行编码转换也好，多少有点麻烦，与其如此，我们不如直接使用properties的xml格式。

```xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
	<comment>系统配置</comment>
	<entry
		key="logo.location"><![cdata[/image/logo/]]></entry>
	<entry
		key="mail.host"><![cdata[webmaster@zlex.org]]></entry>
	<entry
		key="site.name"><![cdata[zlex中文网站]]></entry>
	<entry
		key="welcome"><![cdata[欢迎您，{0}！]]></entry>
</properties>

```

对应原有的properties文件

```properties

#系统配置
logo.location=/image/logo/
mail.host=webmaster@zlex.org
site.name=zlex中文网站
welcome=欢迎您，{0}！

```

这里需要替换**{0}**，可以使用**MessageFormat**，参考如下代码：

```java

private FileInputStream fis;

	@Before
	public void init() {
		try {
			fis = new FileInputStream(new File("config.xml"));
		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void t() {
		Properties properties = new Properties();
		try {
			properties.loadFromXML(fis);
			System.err.println(MessageFormat.format(
					(String) properties.get("welcome"), "snowolf"));
		} catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

```


得到控制台输出：

> 欢迎您，snowolf！

 :D 

因为使用XML格式，不受系统编译影响，不存在中文问题！ :D