1. 资源文件
资源文件都是属性文件,后缀为.properties,内容是键值对形式,有三种命名方式:
1) basename_lauguage_country.properties
2) basename_lauguage.properties
3) basename.properties
其中,basename是资源文件的基础名字,language是语言简称,country是国家简称。
准备两个资源文件hello_zh_CN.properties和hello_en_US.properties:
name=\u5c0f\u5c41\u5b69\u513f
msg=\u4f60\u597d\uff0c{0}\uff01
name=WimpyKid
msg=hello, {0}!
如果资源文件中包含非西方字符,可以使用JDK提供的工具native2ascii将资源文件中的字符转换成unicode编码,避免乱码问题
2. 简单的示例:
package com.huey.i18n;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* 国际化简单小示例
* @version 2013-08-04
* @author huey2672
*
*/
public class Internationalization {
public static void main(String[] args) {
// 创建Locale对象,指定国家/地区和语言
Locale cnLocale = new Locale("zh", "CN");
Locale usLocale = new Locale("en", "US");
// 加载资源包
ResourceBundle rb1 = ResourceBundle.getBundle("hello", cnLocale);
ResourceBundle rb2 = ResourceBundle.getBundle("hello", usLocale);
// 从资源包中获取内容
String msg1 = rb1.getString("msg");
String msg2 = rb2.getString("msg");
String name1 = rb1.getString("name");
String name2 = rb2.getString("name");
// 将消息格式化,动态地为占位符赋值
System.out.println(MessageFormat.format(msg1, name1));
System.out.println(MessageFormat.format(msg2, name2));
}
}
你好,小屁孩儿!
hello, WimpyKid!