使用 Properties 文件配置簡單的數據格式,操作起來非常的方便,Properties 文件存儲最簡單的鍵值對。如建立一個jdbc.properties 文件,內容如下:
jdbcUrl = jdbc:mysql//test
driverClass = driver.mysql.test
userName = abc
passWord =123
使用方法也比較簡單
public UserDaoImpl() {
String resources = "jdbc.properties";
// 將配置文件加載單獨寫成一個函數,將異常處理進行封裝,使代碼整潔
Properties properties = loadProperties(resources);
// 直接用getProperty獲取屬性值
this.jdbcUrl = properties.getProperty("jdbcUrl");
this.driverClass = properties.getProperty("driverClass");
this.userName = properties.getProperty("userName");
this.passWord = properties.getProperty("passWord");
}
private Properties loadProperties(String resources) {
// 使用InputStream得到一個資源文件
InputStream inputstream = this.getClass()
.getResourceAsStream(resources);
// new 一個Properties
Properties properties = new Properties();
try {
// 加載配置文件
properties.load(inputstream);
return properties;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
inputstream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}