Java国际化学习总结

来源:互联网 发布:通达信行情交易软件 编辑:程序博客网 时间:2024/06/08 02:45
hello_zh_CN.properties文件内容如下:hello=你好


hello_en_US.properties文件内容如下:hello=Hello


public static void main(String[] args) {//Locale locale = Locale.getDefault();//可以获得系统默认的国家语言环境/** * 这里得到hello_en_US.properties资源文件 * Hello=你好 */Locale locale = new Locale("en","US");ResourceBundle message = ResourceBundle.getBundle("hello",locale);System.out.println(message.getString("hello"));//输出hello_en_US.properties资源文件中key为hello的值}


输出结果:
Hello



<s:i18n name="hello">// hello_zh_CN.properties    <s:text name="world">// world是定义的key(键)        <s:param>struts2</s:param>// 传递的参数    </s:text>   </s:i18n>   

注意到可以在<s:text>标签中增加<s:i18n> 标签。


在hello_en_US.properties和hello_zh_CN.properties文件中增加


world=hello,{0}



带占位符的消息:

资源文件示例:

msg=你好,{0}!今天是{1}

程序中需要使用MessageFormat类

该类有个静态方法:

format(String pattern,Object … values)

上例对应的JAVA中的字符串输出代码如下:

ResourceBundle bundle = ResourceBundle.getBundle("MyResource", currentLocale);

String msg = bundle.getString("msg");

System.out.println(MessageFormat.format(msg,"Eason", new Date()));



使用类文件代替资源文件:


Java允许使用类文件来代替资源文件,即手动书写代码来实现国际化,


该类要求继承于ListResourceBundle,并重写getContents方法该方法返回Object数组,该数组的每一个项都是key-value对。


类的名字必须为basename_language_contry,这与属性文件的命名相似。


如:

public class MyResource_zh_CN extends ListResourceBundle {private final Object myData[][]= {    {"msg","{0},Hello"}};public Object[][] getContents() {return myData;}}

上面这个是简体中文语言环境下的资源文件,该类可以替换MyResource_zh_CN.properties属性文件。

如果系统同时存在资源文件、类文件,系统将以类文件为主,而不会调用资源文件。




国际化资源文件的分类:

当应用程序很大时,需要国际化的东西会很多,因此需要将国际化资源文件进行分类。

需要知道的是在src中的properties文件是全局资源文件,另外还可以分为包级别的和类级别的

首先看看包级别的

命名规则为package_language_country.properties

新建package_en_US.properties,内容为

username.xml.invalid=package validate information

新建package_zh_CN.properties,内容为

username.xml.invalid=包验证信息

可以看到输出的信息为“包验证信息”,由此可见包级别的国际化资源文件的优先级高于全局国际化资源文件。

 



类级别:

新建RegisterAction_en_US.properties,内容为

username.xml.invalid=class validate information

新建RegisterAction_zh_CN.properties,内容为

username.xml.invalid=类验证信息

此时可以看到输出的信息为“类验证信息”。

由此可以得到国际化资源文件的优先级

全局<包级别<类级别

另外要进行表单的国际化时,要去掉theme="simple"



总结一下显示方法: 

<s:text name="hello"></s:text>

getText("username.invalid") 

<message key="username.xml.invalid"></message>  

<s:textfield name="username" key="username.name"></s:textfield>    

<s:i18n name="hello"></s:i18n>


<s:i18n name="hello"></s:i18n>

标签中包含name,代表着可以定义资源文件的baseName,如可以定义成hello,那么对应着
hello_en_US.properties和hello_zh_CN.properties这两个资源文件。


原创粉丝点击