1. 程式人生 > >MyBatis Java不同方式載入檔案時的路徑格式問題、Mybatis中載入.properties檔案

MyBatis Java不同方式載入檔案時的路徑格式問題、Mybatis中載入.properties檔案

public class LoadPropTest {
    public static void main(String[] args) throws IOException {
        //一、Properties的load方法載入檔案輸入流
        Properties props=new Properties();
        File file1=new File("F:/Program Files/Java/IdeaProjects/MyBatisDemo/src/db.properties");
        File file2=new File("src/db.properties");
        File file3
=new File("src/com/biguo/datasource/jdbc.properties"); //File file4=new File("jdbc.properties"); 報錯,引起了我對相對路徑的思考 FileInputStream fileInputStream1=new FileInputStream(file3); FileInputStream fileInputStream2=new FileInputStream("src/com/biguo/datasource/jdbc.properties"); props.load(fileInputStream2); System.out.println(props.getProperty(
"url")); //二、通過類載入器 載入配置檔案 Properties p = new Properties(); InputStream in = LoadPropTest.class.getClassLoader().getResourceAsStream("com/biguo/datasource/jdbc.properties"); p.load(in); String name = p.getProperty("username"); System.out.println(name);
//三、基名,檔案必須是key=value的properties檔案 ResourceBundle bundle = ResourceBundle.getBundle("com/biguo/datasource/jdbc"); String driver = bundle.getString("username"); System.out.println(driver); } }

   如方式一所示,構造檔案物件File時的路徑,是以工程所在路徑為基礎的。所以指定的檔案在“src”下,都需要新增“src”。

  而方式二和方式三,有個關鍵詞“Resource”,這種情況下通常是以Package路徑作為尋找路徑,預設是以“src”資料夾為基礎的。

  MyBatis中在mybatis-config.xml中載入jdbc.properties時,需要在Configuration的標籤最前面新增如下元素:

<properties resource="com/biguo/datasource/jdbc.properties">
        <!-- 其中的屬性就可以在整個配置檔案中被用來替換需要動態配置的屬性值。 -->
        <!--<property name="password" value="pigu20ing" />-->
</properties>

  這裡也以resource屬性指定載入路徑。

  如果把resource指定為直接放在src檔案下的db.properties檔案,即resource="db.properties",也可以執行成功。

  關於.properties檔案,Java中有對應類Properties。Properties類繼承自Hashtable,是由一組key-value的集合,常用於為各種配置提供資料。

  以下是.properties檔案的內容格式:

  • 註釋內容由 # 或者! 開頭
  • key,value之間用 = 或者 : 分隔。一行中既有=也有:時,第一個(或者=或者:)將作為key,value分隔符。
  • key 不能換行,value可以換行,換行符是\ ,且換行後的\t、空格都會忽略。