java.util.ResourceBundle读取配置文件

来源:互联网 发布:新闻数据分析 编辑:程序博客网 时间:2024/06/17 14:59

java.util.ResourceBundle主要用于读取国际化资源文件:

re s=ResourceBundle.getBundle("cc_fail_message")读取src下的配置文件信息

res.getString("")获取配置文件的值

这个类提供软件国际化的捷径。通过此类,可以使您所编写的程序可以:

         轻松地本地化或翻译成不同的语言 
         一次处理多个语言环境 
         以后可以轻松地进行修改,支持更多的语言环境 
 
说的简单点,这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。
 
使用这个类,要注意的一点是,这个properties文件的名字是有规范的:一般的命名规范是: 自定义名_语言代码_国别代码.properties
如果是默认的,直接写为:自定义名.properties
比如:
myres_en_US.properties
myres_zh_CN.properties
myres.properties
 
当在中文操作系统下,如果myres_zh_CN.properties、myres.properties两个文件都存在,则优先会使用myres_zh_CN.properties,当myres_zh_CN.properties不存在时候,会使用默认的myres.properties。
 
没有提供语言和地区的资源文件是系统默认的资源文件。
资源文件都必须是ISO-8859-1编码,因此,对于所有非西方语系的处理,都必须先将之转换为Java Unicode Escape格式。转换方法是通过JDK自带的工具native2ascii.
 
二、实例
 
定义三个资源文件,放到src的根目录下面(必须这样,或者你放到自己配置的calsspath下面。
 
myres.properties
aaa=good 
bbb=thanks

myres_en_US.properties
aaa=good 
bbb=thanks

myres_zh_CN.properties
aaa=\u597d 
bbb=\u591a\u8c22
 
import java.util.Locale; 
import java.util.ResourceBundle; 

/** 
* 国际化资源绑定测试 

* @author leizhimin 2009-7-29 21:17:42 
*/
 
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(resb1.getString("aaa")); 

                Locale locale3 = new Locale("en""US"); 
                ResourceBundle resb3 = ResourceBundle.getBundle("myres", locale3); 
                System.out.println(resb3.getString("aaa")); 
        } 
}
 
运行结果:
好 
好 
good 

Process finished with exit code 0
 
如果使用默认的Locale,那么在英文操作系统上,会选择myres_en_US.properties或myres.properties资源文件。

0 0