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")); 
相關文章
相關標籤/搜索