最近在Mybatis框架中使用到了讀取properties配置文件,上網查閱了一番讀取方法,比較亂,現在選擇兩種常用的進行說明。
以下測試均在eclipse中,並且使用Junit進行測試。
(1)使用getResourceAsStream()方法讀取配置文件
(2)使用InputStream()流去讀取配置文件
一、以下是工程結構:
在本工程中包含4個不同路徑的配置文件。
1.與測試文件不同的包中的配置文件
2.與測試文件同一個包中的配置文件
3根目錄下面的配置文件
4.不同src下的配置文件
二、讀取properties
1.讀取和測試類同一個包下的配置文件的兩種方法
@Test
public void test01() throws IOException{
InputStream is =PropertiesTest.class.getResourceAsStream("sh.properties");
//Java當中有的工具類
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("shxt"));
}
@Test
public void test02() throws IOException{
InputStream is = new BufferedInputStream(new FileInputStream("src/com/shxt/test/sh.properties"));
//Java當中有的工具類
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("shxt"));
}
2.讀取src根目錄下的配置文件的兩種方法
@Test
public void test03() throws IOException{
InputStream is = PropertiesTest.class.getClassLoader().getResourceAsStream("shxt.properties");
//Java當中有的工具類
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("shxt"));
}
@Test
public void test04() throws IOException{
InputStream is = new BufferedInputStream(new FileInputStream("src/shxt.properties"));
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("vip"));
}
3.讀取另一個包下的配置文件的兩種方法
@Test
public void test05() throws IOException{
InputStream is = PropertiesTest.class.getClassLoader().getResourceAsStream("com/shxt/other/s.properties");
//Java當中有的工具類
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("shxt"));
}
@Test
public void test07() throws IOException{
InputStream is = new BufferedInputStream(new FileInputStream("src/com/shxt/other/s.properties"));
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("vip"));
}
4.讀取另一個src文件夾下的配置文件的兩種方法
@Test
public void test08() throws IOException{
InputStream is = PropertiesTest.class.getClassLoader().getResourceAsStream("shx.properties");
//Java當中有的工具類
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("vip"));
}
@Test
public void test06() throws IOException{
InputStream is = new BufferedInputStream(new FileInputStream("other_src/shx.properties"));
Properties props = new Properties();
props.load(is);
System.out.println(props.getProperty("vip"));
}
另外附上properties文件中的代碼
shxt=四海興唐
vip=超越40
jdbc.mysql.driver=com.mysql.jdbc.Driver
三、總結
1.在使用getResourceAsStream()方法的四個測試中,只有在讀取和測試類同一個包下的配置文件時(即第一種的第一個測試),沒有使用getClassLoader()方法來加載類加載器。
2.在使用getResourceAsStream()方法的四個測試中,只有讀取另一個包下的配置文件時(即第三種的第一個測試),需要寫全路徑,其他狀態只需要寫文件名。
3.在使用InputStream()流去讀取配置文件的四個測試中,路徑均要從src目錄開始寫。
注:本文均爲個人理解,如有錯誤,歡迎指正