java国际化

来源:互联网 发布:ios11下载不了软件 编辑:程序博客网 时间:2024/06/05 01:52

 

java国际化  本文来自:http://www.javaarch.net/jiagoushi/477.htm

国际化是为了让应用程序能够兼容多种语言而不需要修改源代码,有时我们使用i18n代表国际化internationalization 的意思,那是因为internationalization 单词第一个字母i和最后一个字母n之间有18个字母。

国际化程序能够带来的好处:

1.本地时间,支持国际化程序,时间相关问题在多种语言地区之间就不会存在。

  1. GUI程序的文本信息

  2. 能够支持新语言而不需要重新编译

  3. 时间和汇率跟本地化相关

  4. 能够快速本地化

未进行国际化处理的程序:

 

public class NotI18N {    static public void main(String[] args) {        System.out.println("Hello.");        System.out.println("How are you?");        System.out.println("Goodbye.");    }}

 输出:

 

% java I18NSample fr FRBonjour.Comment allez-vous?Au revoir.

 经过国际化处理的程序:

import java.util.*;public class I18NSample {    static public void main(String[] args) {        String language;        String country;        if (args.length != 2) {            language = new String("en");            country = new String("US");        } else {            language = new String(args[0]);            country = new String(args[1]);        }        Locale currentLocale;        ResourceBundle messages;        currentLocale = new Locale(language, country);        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);        System.out.println(messages.getString("greetings"));        System.out.println(messages.getString("inquiry"));        System.out.println(messages.getString("farewell"));    }}

 输出:

% java I18NSample en USHello.How are you?Goodbye.

 在java中怎么让程序支持国际化

1.创建properties文件 包含跟环境相关的文本信息

比如:默认版本的MessagesBundle.properties

greetings = Hellofarewell = Goodbyeinquiry = How are you?

 支持Franch的MessagesBundlefrFR.properties

greetings = Bonjour.farewell = Au revoir.inquiry = Comment allez-vous?

2.设置Locale Local是跟语言和地区相关的设置

比如设置语言为English,地区为US aLocale = new Locale("en","US"); 设置Canada和Franch的版本

caLocale = new Locale("fr","CA");frLocale = new Locale("fr","FR");   

然后通过传入参数设置:

String language = new String(args[0]);String country = new String(args[1]);currentLocale = new Locale(language, country);

3.创建ResourceBundle

messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);

locale第一个参数对应到语言,第二个是地区,跟下面下划线的参数对应

MessagesBundle_en_US.propertiesMessagesBundle_fr_FR.propertiesMessagesBundle_de_DE.properties

4.通过ResourceBundle的方法获取对应的文本信息

String msg1 = messages.getString("greetings");

这样的话新增一个语言或者地区的不同文本就很简单了。

然后在实际应用中,下面的各个部分都需要作为checklist检查是否需要国际化

MessagesLabels on GUI componentsOnline helpSoundsColorsGraphicsIconsDatesTimesNumbersCurrenciesMeasurementsPhone numbersHonorifics and personal titlesPostal addressesPage layouts

 

 

原创粉丝点击