MyBatis Java不同方式加載文件時的路徑格式問題、Mybatis中加載.properties文件
阿新 • • 發佈:2018-11-28
eap con 需要 ssl 換行符 input .get adp getprop
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、空格都會忽略。
MyBatis Java不同方式加載文件時的路徑格式問題、Mybatis中加載.properties文件