ResourceBundle提供了一种本地化资源的机制。

大致原理:

提供不同语言或者不同国家的properties文件。

假设properties文件名为message,不同语言的文件名对应为:message_{language}_{country}.properties。

language以及country可以省略。如果全部省略,就是默认文件。

ResourceBundle提供了一个getBundle的静态方法,入参是properties文件的文件名和Local对象。

该方法会在classpath下寻找对应的本地化资源文件。

顺序:

优先查找后缀为language以及country的资源文件;

如果没有,查找后缀为language的资源文件;

如果没有,按照当前系统的Local实例变量查找对应的资源文件,比如我系统是中文,就按照Local("zh","CN")来找;

如果还没有,就使用默认资源文件。

public class BundleMain {
public static void main(String args[]) {
System.out.println(Locale.getDefault());

ResourceBundle bundle = ResourceBundle.getBundle("message", Locale.getDefault());
System.out.println(bundle.getString("key1"));

bundle = ResourceBundle.getBundle("message", Locale.US);
System.out.println(bundle.getString("key1"));

bundle = ResourceBundle.getBundle("message", Locale.UK);
System.out.println(bundle.getString("key1"));

bundle = ResourceBundle.getBundle("message", Locale.FRANCE);
System.out.println(bundle.getString("key1"));
}
}

message.properties:

key1=defaultValue

message_en.properties:

key1=en_Value

message_en_US.properties:

key1=en_US_Value

当前系统的Local为:zh_CN

输出:

zh_CN
defaultValue
en_US_Value
en_Value
defaultValue

Process finished with exit code 0

如果提供了一个message_zh_CN.properties文件,那么之前查到message.properties文件的就变为message_zh_CN.properties文件的内容。

 

注意点:

getBundle方法传入的资源文件名不能带“.prop”