得到配置文件內容,其最大的問題就是文件路徑的定位: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);
二、使用java.util.ResourceBundle類的getBundle()方法 資源
ResourceBundle這個類提供軟件國際化的捷徑 。使用這個類,要注意的一點是,這個properties文件的名字是有規範的:get
通常的命名規範是: 自定義名_語言代碼_國別代碼.properties, event
定義資源文件,放到src的根目錄下面:(注意不在src的根目錄下,路徑分割符用的是 " . ")class
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"));