工具类:AbstractLanguage
package common.util;
import java.util.Locale;
import java.util.ResourceBundle;
public abstract class AbstractLanguage{
@SuppressWarnings("unused")
private String language;
@SuppressWarnings("unused")
private String region;
private Locale locale;
private ResourceBundle resourceBundle;
@SuppressWarnings("unused")
private String fileName;
//默认国际化配置文件的路径
private static final String FILE_NAME="res";
AbstractLanguage(String language,String region){
this(language,region,FILE_NAME);
}
AbstractLanguage(String language,String region,String fileName){
this.language=language;
this.region=region;
this.fileName=fileName;
locale=new Locale(language,region);
resourceBundle=ResourceBundle.getBundle(fileName, locale);
}
protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
public abstract String getLocalString(String code);
/**
* 获得国际化的语言类实例,可以通过参数进行设定
* @param language
* @param region
* @return
*/
public static AbstractLanguage getLanguage(String language,String region){
return getLanguage(language,region,FILE_NAME);
}
public static AbstractLanguage getLanguage(String language,String region,String fileName){
return new AbstractLanguage(language,region,fileName){
public String getLocalString(String code) {
return super.getResourceBundle().getString(code);
}
};
}
}
测试类
package common.util;
public class Test {
public static void main(String[] args) {
/*
* 默认路径(工程根目录)下的国际化配置文件
* res.properties
* res_ch_zh.properties
* res_en_us.properties
*
*/
System.out.println(AbstractLanguage.
getLanguage("ch", "zh").getLocalString("USD"));
System.out.println(AbstractLanguage.
getLanguage("en", "us").getLocalString("USD"));
System.out.println(AbstractLanguage.
getLanguage("een", "us").getLocalString("USD"));
/*
* 指定路径下的国际化配置文件 注意包路径用. 不用/
* res.properties
* res_ch_zh.properties
* res_en_us.properties
*
*/
System.out.println(AbstractLanguage.
getLanguage("ch", "zh","common.util.res").getLocalString("USD"));
System.out.println(AbstractLanguage.
getLanguage("en", "us","common.util.res").getLocalString("USD"));
System.out.println(AbstractLanguage.
getLanguage("een", "us","common.util.res").getLocalString("USD"));
}
}
项目根路径下的配置文件:
res.properties
内容:
USD=in default usd
res_ch_zh.properties
内容:
USD=人民币
res_en_us.properties
内容:
USD=dollar