項目中有時候需要從配置文件中加載各種配置屬性。
1.利用FileInputStream
這種方式比較適合從任意路徑加載配置文件,文件路徑是絕對路徑。直接看代碼
//初始化資源加載器,boolean值指示加載成功還是失敗 private static boolean initialize(){ try{ try{ stream = new FileInputStream("E:/info.properties"); info = new Properties(); info.load(stream); }finally { if(stream != null) stream.close(); } }catch (Exception e){ e.printStackTrace(); return false; } return true; } //獲取配置信息 public static String getProperties(String key){ return info.getProperty(key); } public static void main(String[] args) { if(!initialize())return; System.out.println(getProperties("key")); }
2.利用ClassLoader對象的getResourceAsStream()
底層使用了類加載器加載,這種方式只能從classpath下加載配置文件,即src目錄下的文件,路徑是相對路徑,從src開始寫起
//初始化資源加載器,boolean值指示加載成功還是失敗 private static boolean initialize(){ try{ try{ stream = ResourceUtil.class.getClassLoader() .getResourceAsStream("resources/info.properties"); info = new Properties(); info.load(stream); }finally { if(stream != null) stream.close(); } }catch (Exception e){ e.printStackTrace(); return false; } return true; } //獲取配置信息 public static String getProperties(String key){ return info.getProperty(key); }
文件的存放路徑如下:
用這種方式去加載絕對路徑下的文件會出現錯誤,應避免使用。