java 国际化 properties_Java 国际化:用 XML 来代替 properties

Java 的国际化特性缺省是用 .properties 文件来保存非英文内容的,它看上去是这个洋子:

75ee1f9e99602b1875db5067197ea0d0.png

果然很令人深恶痛绝是吧。这里介绍一个办法,用 .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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值