新建一個普通的 Java 專案,在 src 目錄下放一個 config.properties 檔,內容只有一句話:
driverURL = jdbc:mysql://127.0.0.1:3306/evan
讀取這個配置檔的 Java 程式碼如下。關鍵在於用 getResourceAsStream 搭配以「/」開頭的路徑,直接從 classpath 根目錄(即 src)讀取檔案,再用 Properties 物件載入並取出對應的鍵值:
package com.evan;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) throws IOException {
InputStream is = ReadProperties.class.getResourceAsStream("/config.properties");
Properties properties = new Properties();
properties.load(is);
is.close();
String driverURL = properties.getProperty("driverURL");
/*
* 輸入結果為:jdbc:mysql://127.0.0.1:3306/evan
*/
System.out.println(driverURL);
}
}
專案的目錄結構請參考上圖。