基于gettext的国际化/本地化方案

               我在整理wordpress 博客主题的 mo/po 语言包时, 发现wordpress 用到了  gettext ,这其实是一个通用的 国际化/本地化 方案 . 查看它的文档发现 :  它支持几乎所有开发语言, 这里仅仅以java为例说明其基本的使用方法(其他语言可能更简单,具体查看文档):

    第一步, 我还是以Hello World 程序为例

//test/Hello.java

package test;

public class Hello

{

   public static void main(String[] args) {

        System.out.println("Hello World !");

   }

}

    第二步,将需要国际化的部分通过 _() 标记起来,当然目前是编译不通过的

//test/Hello.java

package test;

public class Hello

{

   public static void main(String[] args) {

        System.out.println(_("Hello World !"));

   }

}

   第三步: 然后使用xgettext工具提取需要翻译的字符串,保存到.pot文件, "-k_ "中的 "_"就是前面代码中的标记.

chaoskey@ubuntu:~$ xgettext -k_ -o gettext_hello.pot -L java  Hello.java

得到 gettext_hello.pot 文件中 有:

#: Hello.java:4

msgid "Hello World !"

msgstr ""

    第四步, 将 .pot 文件交给 本地化人员翻译(注意,要修改.pot 文件中字符集编码的设置,比如这里可以设置为:utf-8):

msgid "Hello World !"

msgstr "世界,你好!"

    第五步: 为某种语言(这里是简体中文:zh_CN)

   1) 第一次使用 msginit

chaoskey@ubuntu:~$ msginit -i gettext_hello.pot -l zh_CN -o gettext_hello_zh_CN.po

   2) 以后只要使用 msgmerge

chaoskey@ubuntu:~$ msgmerge -U gettext_hello_zh_CN.po gettext_hello.pot

    第六步,生成java资源文件:

chaoskey@ubuntu:~$ msgcat -p -o gettext_hello_zh_CN.properties gettext_hello_zh_CN.po

    第七步,增加一个GettexthelloUtils工具类,并且修改Hello.Java 代码

//test/GettexthelloUtils.java

package test;

import java.util.Locale;

import java.util.ResourceBundle;

class GettexthelloUtils {

    private static ResourceBundle bundle =

        ResourceBundle.getBundle("gettext_hello");

    public static String _(String s) {

        return bundle.containsKey(s) ? bundle.getString(s) : s;

    }

}

//test/Hello.java

package test;

import static test.GettexthelloUtils._;

import java.util.Locale;

import java.util.ResourceBundle;

public class Hello

{

   public static 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 = new Locale(language, country);

        Locale.setDefault(currentLocale);

        System.out.println(_("Hello World !"));

   }

}

    第八步: 编译运行

chaoskey@ubuntu:~$ javac -d . test/Hello.java

chaoskey@ubuntu:~$ java -cp . test.Hello zh CN

世界,你好!

 美女主持AmandaS

转载请注明:来自無處不在
本文地址:http://blog.chaoskey.com/2009/02/15/480



0 条评论

我要留言