JAVA加载properties配置文件

 

得到配置文件内容,其最大的问题就是文件路径的定位:java

经过ClassLoader去加载资源。参数须要从classpath的入口来算起。也就是说须要取全路径名称。ide

    String  path =   当前类名.class.getClassLoader().getResource("").toURI().getPath() ;  //默认的是到src文件夹下spa

     或者操作系统

     String  path =   当前类名.getClassLoader().getResourceAsStream("conf/key-conf.properties"); //src文件夹下的conf/key-conf.propertiescode

 

1、使用java.util.Properties类的load()方法 blog

 

InputStream in = lnew BufferedInputStream(new FileInputStream(name));   
Properties p = new Properties();   
p.load(in);  
View Code

 

二、使用java.util.ResourceBundle类的getBundle()方法  资源

 ResourceBundle这个类提供软件国际化的捷径 。使用这个类,要注意的一点是,这个properties文件的名字是有规范的:get

通常的命名规范是: 自定义名_语言代码_国别代码.properties, event

若是是默认的,直接写为: 自定义名.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。

定义资源文件,放到src的根目录下面:(注意不在src的根目录下,路径分割符用的是 " . ")class

myres.properties
aaa=good 
bbb=thanks

myres_en_US.properties
aaa=good 
bbb=thanks

myres_zh_CN.properties
aaa=\u597d 
bbb=\u591a\u8c22
                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")); 
相关文章
相关标签/搜索