Java國際化主要通過如下3個類完成
java.util.ResourceBundle:用於加載一個資源(配置文件)
java.util.Locale:對應一個特定的國家/區域、語言環境。
java.text.MessageFormat:用於將消息格式化
//根據操作系統環境獲取語言環境
Locale locale = Locale.getDefault();
System.out.println(locale.getCountry());//輸出國家代碼
System.out.println(locale.getLanguage());//輸出語言代碼s
//加載國際化資源(classpath下resources目錄下的messages.properties,如果是中文環境會優先找messages_zh_CN.properties)
ResourceBundle rb = ResourceBundle.getBundle("resources.messages", locale);
String retValue = rb.getString("102");//101是messages.properties文件中的key
System.out.println(retValue);
//信息格式化,如果資源中有{}的參數則需要使用MessageFormat格式化,Object[]爲傳遞的參數,數量根據資源文件中的{}個數決定
String value = MessageFormat.format(retValue,new Object[]{100,200});
System.out.println(value);
使用工具類ResourcesUtil,從資源文件中取配置信息:
1.將所有的信息統一配置資源文件裏面,在java代碼只需要調用工具類取出配置信息,防止硬編碼。