項目應對外國和中國客戶,就要求通過配置,實現文字的轉換,這個過程,在java實現非常簡單,
主要通過一個設定檔定義language.txt,使用的語言:
檔案內容為:
language=zh_CN
在把編輯好的國際化的檔案放到java的package下面.
resource.properties中的內容為:
請注意, 在{0} 發生 {1} 事故, 車輛行駛緩慢!
需要轉換成unicode的編碼方式,轉換的命令為:
native2ascii -encoding gb2312 resource.properties resource_cn.properties
可以通過java.text.MessageFormat來對文字進行即時的渲染,修改。
代碼如下:
package app.language.global;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
public class globalLanguageImpl {
static String defaultMessage;
static Locale currentLocale;
static ResourceBundle messages;
static InputStream is;
static Properties prop;
public static void getProp(){
is = globalLanguageImpl.class.getClassLoader().getResourceAsStream("app/language/global/language.txt");
prop = new Properties();
try {
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String formatMessage(String template, Object[] params, Locale currentLocale) {
MessageFormat formatter = new MessageFormat("");
formatter.setLocale(currentLocale);
formatter.applyPattern(template);
String output = formatter.format(params);
return output;
}
public static void main(String[] args) {
getProp();
String[] resource = ((String)prop.get("language")).split("_");
String language = resource[0].toLowerCase();
String country = resource[1].toUpperCase();
currentLocale = new Locale(language, country);
messages = ResourceBundle.getBundle("app.language.global.resource", currentLocale);
defaultMessage = messages.getString("default_message");
Object[] params = { "London golden road", "road works" };
String alertInfo = formatMessage(defaultMessage, params, currentLocale);
System.out.println("======================" + language + "_" + country);
System.out.println("======================" + alertInfo);
}
}
產生的結果為:
======================zh_CN
======================請注意, 在 London golden road 發生 road works 事故, 車輛行駛緩慢!
通過以上的工作,就可以通過修改設定檔language.txt中的內容,來達到改變顯示語言的目的了。
由於不用重新編譯,由客戶自己就能修改配置,
如英語國家可以修改為:
language=en_US
在重新起動項目就可以了。
在國際化的過程中,由ResourceBundle來負責尋找複合條件的國際化文字檔案,開發人員的工作就是在後台和頁面有文字顯示的部分全部換成messages.getString("default_message"); 的形式即可。
如果是jsp頁面,基本結構如下:
<%@page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:bundle basename="app.language.global.resource">
在需要用到文字的地方的寫法:
<fmt:message key='copyright'/>
<fmt:message key='logout'/>
很簡單的,pageEncoding="UTF-8"這樣既可以支援中文,也可以支援英文,不錯的選擇,否則國際化也就沒有意義了。