獲取工程中的Properties檔案
阿新 • • 發佈:2018-12-10
獲取工程下的Properties檔案大體有2種方式,取決於你的properties檔案是放在工程中的哪個位置,下面分別介紹如下:
1、在同一個包下,如果此時不在同一包下那麼會報 null point Exception:
此時可以通過如下2種方式 程式碼獲取:
@Test public void getProperties(){ InputStream is = this.getClass().getResourceAsStream("/com/demo/c3p0/db.properties"); Properties p = new Properties(); try { p.load(is); String driver =p.getProperty("jdbcDriver"); String url =p.getProperty("jdbcUrl"); String userName =p.getProperty("jdbcUserName"); String passWord =p.getProperty("jdbcPassword"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void getProperties2(){ InputStream is = PropertiesUtils.class.getResourceAsStream("/com/demo/c3p0/db.properties"); Properties p = new Properties(); try { p.load(is); String driver =p.getProperty("jdbcDriver"); String url =p.getProperty("jdbcUrl"); String userName =p.getProperty("jdbcUserName"); String passWord =p.getProperty("jdbcPassword"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2、在不同一包下,這種也是我們最常用的配置方式
此時通過如下程式碼獲取:
在程式碼中getClassLoader()是通過類載入器獲取類路徑(clsasspath)下的檔案
@Test public void getProperties3(){ InputStream is = this.getClass().getClassLoader().getResourceAsStream("db.properties"); Properties p = new Properties(); try { p.load(is); String driver =p.getProperty("jdbcDriver"); String url =p.getProperty("jdbcUrl"); String userName =p.getProperty("jdbcUserName"); String passWord =p.getProperty("jdbcPassword"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }