您的位置:首页 > 编程语言 > Java开发

42、Java国际化

2016-06-15 15:49 621 查看
简介  

  国际化的英文单词是Internationalization,有时检测I18N,类似于I18N还有L10N,是Location本地化的简写。

Java或计划主要通过如下三个类实现

  1、java.util.ResourceBoundle:用于加载国家和语言资源包

  2、java.utl.Local:用于封装特定的国家/区域、语言环境

  3、java.text.MessageFormat:用于格式化带占位的字符串

资源文件的命名方式

  1、baseName_language_country.properties

  2、baseName_language.properties

  3、baseName.properties

  其中baseName是资源文件的基本名称,用户可以随意指定;而language和country是不可以随意变化,必须是java所支持的语言和国家。

  

获取Java支持的国家和语言

  通过Locale的getAvailableLocales可以获取所有Java支持的国家和语言

Locale[] localeArr=Locale.getAvailableLocales();
for (Locale locale : localeArr) {

System.out.println(locale.getCountry()
+" "+locale.getDisplayCountry()
+" "+locale.getLanguage()
+" "+locale.getDisplayLanguage()
+" "+locale.getDisplayName()
);
}


编写properties文件

第一个文件:message_en_US.properties.该文件内容为:

hello=WelCome You!


第二个文件:message.properties

hello=你好!


【注意】对于properties文件,该文件只能存储西欧字符,其它非西欧字符需要已Unicode编码方式保存。在java中提过了一个native2ascii工具来处理。该工具位于JDK/bin下。使用如下

native2ascii 资源源文件 目的资源文件




打开message_zh_CN.properties文件内容如下:



获取properties中的值

package action;

import java.util.Locale;
import java.util.ResourceBundle;

public class Test2 {

@org.junit.Test
public void test(){
ResourceBundle bundle=ResourceBundle.getBundle("message", Locale.getDefault());
String hello=bundle.getString("hello");
}
}


MessageFormat处理占位符的字符串

  如果properties文件中字符串需要外界传入参数,则需要使用到占位符,不如某个消息为:

欢迎【caoyc】用户登录,当前时间:2016-06-15 16:03


  上面的caoyc和时间都需要外界传入参数,所以在properties中需要这样设计

msg=欢迎【{0}】用户登录,当前时间:{1}


  Java代码:

package action;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test2 {

@org.junit.Test
public void test(){
ResourceBundle bundle=ResourceBundle.getBundle("message", Locale.getDefault());
String msg=bundle.getString("msg");
MessageFormat.format(msg, "caoyc",new Date());
}
}


  通过MessageFormat.format方式对msg进行传值,该方法包含一个可变参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: