Java 的国际化特性缺省是用 .properties 文件来保存非英文内容的,它看上去是这个洋子:
果然很令人深恶痛绝是吧。这里介绍一个办法,用 .xml 文件来代替 .properties 文件,同样用 ResourceBundle 来实现国际化。
首先 ResourceBundle 类其实是很灵活的,并不是只能读取 .properties 文件。要让它读取其他格式的文件的话,只需要编写自己的 ResourceBundle.Control 子类就可以了。下面是一个用来读取 .xml 文件的实现:
// code from http://www.java2s.com/Code/Java/JDK-6/XMLresourcebundle.htm
public class XMLResourceBundleControl extends ResourceBundle.Control {
private static String XML = "xml";
public List getFormats(String baseName) {
return Collections.singletonList(XML);
}
public ResourceBundle newBundle(String baseName, Locale locale, String format,
ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException,
IOException {
if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
throw new NullPointerException();
}
if (!format.equals(XML)) {
return null;
}
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, format);
URL url = loader.getResource(resourceName);
if (url == null) {
return null;
}
URLConnection connection = url.openConnection();
if (connection == null) {
return null;
}
if (reload) {
connection.setUseCaches(false);
}
InputStream stream = connection.getInputStream();
if (stream == null) {
return null;
}
BufferedInputStream bis = new BufferedInputStream(stream);
ResourceBundle bundle = new XMLResourceBundle(bis);
bis.close();
return bundle;
}
}
class XMLResourceBundle extends ResourceBundle {
private Properties props;
XMLResourceBundle(InputStream stream) throws IOException {
props = new Properties();
props.loadFromXML(stream);
}
protected Object handleGetObject(String key) {
return props.getProperty(key);
}
public Enumeration getKeys() {
Set handleKeys = props.stringPropertyNames();
return Collections.enumeration(handleKeys);
}
}
接下来用它来创建 ResourceBundle:
ResourceBundle bundle = ResourceBundle.getBundle("strings", new XMLResourceBundleControl());
上面这个例子就能读取 classpath 下的 strings.xml 文件了。如果是其他的语言,命名规则和 .properties 一样,例如简体中文就用 strings_zh_CN.xml。那么 XML 文件的内容是什么样的呢,下面是个例子:
Connections
Host:
Name:
Pass phase (Optional):
Port:
本文由 捏造的信仰 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2017/04/11 07:05