| 類別 | 職責 | 典型場景 |
|---|---|---|
DateFormat | 日期/時間格式化與解析 | 多國日期顯示(如 yyyy-MM-dd vs MM/dd/yyyy) |
NumberFormat | 數字、貨幣、百分比格式化 | 金額顯示(¥1,234.56 vs $1,234.56 vs 1.234,56 €) |
MessageFormat | 帶佔位符模板字串格式化 | 動態訊息組裝:{0} 歡迎您,餘額 {1} |
ResourceBundle | 載入屬性檔(.properties) | 多語言資源隔離:messages_zh_TW.properties |
基礎名稱.properties # 預設
基礎名稱_語言代碼.properties # 如 messages_zh.properties
基礎名稱_語言代碼_國家代碼.properties # 如 messages_zh_TW.properties
查找策略:zh_TW → zh → 默認,層層回退。
屬性檔須為 ISO-8859-1 編碼,中文需用 native2ascii 轉 Unicode 轉義(如 \u65E5\u671F),IDE 通常自動處理。
@Test
public void i18nDemo() {
Locale locale = Locale.TRADITIONAL_CHINESE; // 或 Locale.US, Locale.JAPAN 等
// 1. 載入資源包
ResourceBundle bundle = ResourceBundle.getBundle("i18n.messages", locale);
String dateLabel = bundle.getString("date"); // "日期"
String salaryLabel = bundle.getString("salary"); // "薪資"
// 2. 日期格式化
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale);
String dateStr = df.format(new Date()); // "2024年12月25日"
// 3. 貨幣格式化
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
String salaryStr = nf.format(1234567.89); // "NT$1,234,568"
// 4. 訊息模板組裝
String pattern = "{0}: {1}, {2}: {3}";
String result = MessageFormat.format(pattern, dateLabel, dateStr, salaryLabel, salaryStr);
// 輸出:日期: 2024年12月25日, 薪資: NT$1,234,568
System.out.println(result);
}
DateFormat.parse()、NumberFormat.parse() 將字串還原為物件new SimpleDateFormat("yyyy/MM/dd HH:mm", locale)request.getLocale() 獲取瀏覽器偏好語言,配合攔截器/Filter 自動注入ResourceBundle 內建快取,生產環境可配合 ResourceBundle.Control 自訂重載週期Locale 建構錯誤(如 new Locale("zh", "CN") vs Locale.SIMPLIFIED_CHINESE)Currency 導致符號錯位SimpleDateFormat 非線程安全,需用 ThreadLocal 或 JDK 8+ DateTimeFormatterJava 國際化核心在於「資源外部化 + Locale 驅動格式化」。掌握四大類別協作模式,配合 Spring 的 MessageSource、LocaleResolver,即可構建企業級多語言應用。