java国际化(转)

May 3, 2007

國際化的英文是Internationalization,因為單字中總共有18個字母,簡稱I18N,目的是讓應用程式可以應地區不同而顯示不同的訊息,最基本的就是讓不同語系的使用者可以看到屬於自己語系的訊息,像是英文語系的看到英文內容,而中文語系的可以看到中文的內容。

為了在應用程式中表示一個區域,Java提供有java.util.Locale類,一個Locale實例包括了語系資訊與區域資訊,例如說”en”表示英文語系的國家,這個字母組合是在 ISO 639 中定義的,而區域資訊則是像”US”表示美國,這個字母組合則是在 ISO 3166 中定義的。

您可以這麼新增一個Locale的實例:

Locale locale = new Locale(”zh”, “TW”);

如何將Locale用於訊息綁定呢?當您使用ResourceBundle.getBundle()方法時,預設就會自動取得電腦上的語系與區域訊息,而事實上訊息檔案的名稱由basename加上語系與地區來組成,例如:

basename.properties
basename_en.properties
basename_zh_TW.properties

沒有指定語言與地區的basename是預設的資源檔名稱,當沒有提供專用的語系、區域訊息檔案時,就會找尋預設的資源檔案。

如果您想要提供繁體中文的訊息,由於訊息資源檔必須是ISO-8859-1編碼,所以對於非西方語系的處理,必須先將之轉換為Java Unicode Escape格式,例如您可以先在訊息資源檔中寫下以下的內容:

messages_zh_TW.txt
onlyfun.caterpillar.welcome=哈囉onlyfun.caterpillar.name=世界

然後使用JDK的工具程式native2ascii來轉換,例如:

native2ascii -encoding Big5 messages_zh_TW.txt messages_zh_TW.properties

轉換後的內容會如下:

messages_zh_TW.properties
onlyfun.caterpillar.welcome=\u54c8\u56c9onlyfun.caterpillar.name=\u4e16\u754c

將這個檔案放於classpath可以存取的到的位置,您也可以提供預設的訊息檔案:

messages.properties
onlyfun.caterpillar.welcome=Helloonlyfun.caterpillar.name=World

來測試一下訊息檔案,我所使用的作業系統是語系設定是中文,區域設定是台灣,當我使用下面的程式時:

ResourceBundleDemo.java
package onlyfun.caterpillar; import java.util.ResourceBundle;public class ResourceBundleDemo { public static void main(String[] args) {
ResourceBundle resource = ResourceBundle.getBundle(”messages”);
System.out.print(resource.getString( “onlyfun.caterpillar.welcome”) + “!”); System.out.println(resource.getString( “onlyfun.caterpillar.name”) + “!”); }}

會使用預設的語系”zh”與區域設定”TW”,所以就會找尋messages_zh_TW.properties的內容,所以會顯示以下的訊息: 哈囉!世界!

在使用ResourceBundle.getBundle()時可以給定Locale實例作為參數,例如若您想提供 messages_en_US.properties,並想要ResourceBundle.getBundle()取得這個檔案的內容,則可以如下撰寫:

Locale locale = new Locale(”en”, “US”);
ResourceBundle resource =
ResourceBundle.getBundle(”messages”, locale);

則取得的訊息會是messages_en_US.properties的內容。

Comments »

The URI to TrackBack this entry is: http://lwj.blogsome.com/2007/05/03/p32/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.