一、常用加载资源文件方式
程序中资源文件加载、文件读写操作使用率非常频繁。一般资源文件加载方式都是基于class的类加载器找到资源文件路径,使用fileStream、或者property对象获取资源文件内容。
String filePath = ReportMail.class.getClassLoader().getResource("resourcesconfig.properties").getPath();
props.load(new FileInputStream(filePath));
domainName = props.getProperty("reportFilepath");
但是还有一种比较简单方式,一行代码搞定。
domainName=ResourceBundle.getBundle("resourcesconfig").getString("reportFilepath");
//或者加两层文件路径
ResourceBundle conf=ResourceBundle.getBundle("config/fnconfig/fnlogin");
ResourceBundle和Properties都适用于读取properties文件,两者底均通过类加载器映射到某路径,获取文件。ResourceBundle主要实现了国际化,针对内容为不同语言的properties文件进行内容转换。
二、ResourceBundle国际化
例如创建一个prop文件,myres.properties,内容为aaa=good
使用ResourceBundle根据不同的Locale 地域对象加载相同的此文件,输出会根据不同的地区Locale输出该地区所能识别的语言。/**
* 国际化资源绑定测试
*
*/
public class TestResourceBundle {
public static void main(String[] args) {
Locale locale1 = new Locale("zh", "CN");
ResourceBundle resb1 = ResourceBundle.getBundle("myres", locale1);
System.out.println(resb1.getString("aaa")); //好
ResourceBundle resb2 = ResourceBundle.getBundle("myres", Locale.getDefault());
System.out.println(resb2.getString("aaa")); //好
Locale locale3 = new Locale("en", "US");
ResourceBundle resb3 = ResourceBundle.getBundle("myres", locale3);
System.out.println(resb3.getString("aaa")); //good
}
}
Locale.default是获取本机当前语言返回。故还是中文。
三、Locale类
Locale类也是比较有意思,创建完Locale 后,就可以查询有关其自身的信息。使用 getCountry 可获取 ISO 国家代码,使用 getLanguage 则获取 ISO 语言代码。可用使用 getDisplayCountry 来获取适合向用户显示的国家名。同样,可用使用 getDisplayLanguage 来获取适合向用户显示的语言名。
Locale locale1 = new Locale("zh", "CN");
System.out.println(locale1.getCountry());//CN
System.out.println(locale1.getLanguage());//zh
System.out.println(locale1.getDisplayCountry());//中国
System.out.println(locale1.getDisplayLanguage());//中文
System.out.println(locale1.getDisplayName());//中文 (中国)