根据javadoc,使用 ISO-8859-1 读取属性文件。
.. 输入/输出流采用 ISO 8859-1 字符编码进行编码。不能用这种编码直接表示的字符可以使用 Unicode 转义来编写;转义序列中只允许使用单个 'u' 字符。native2ascii 工具可用于将属性文件与其他字符编码进行转换。
除了使用 native2ascii 工具将 UTF-8 属性文件转换为 ISO-8859-1 属性文件之外,您还可以使用自定义ResourceBundle.Control
,以便您可以控制属性文件的加载并在那里使用 UTF-8。这是一个启动示例:
public class UTF8Control extends Control {
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
}
}
按如下方式使用它:
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());
这样你就不需要使用 native2ascii 工具了,你最终会得到更好的可维护的属性文件。
也可以看看: