在 Java 專案中,資料庫連線參數、系統設定常外部化至 .properties 檔案,避免硬編碼。本文示範如何正確載入與讀取屬性檔。
jdbc.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc.url=jdbc:microsoft:sqlserver://10.0.0.168:1433;
jdbc.username=sa
jdbc.password=sa
jndi.databaseName=northwind
package zy.pro.wd.demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo {
public void testPropertiesFile() {
try (FileInputStream fis = new FileInputStream("src/jdbc.properties")) {
Properties props = new Properties();
props.load(fis); // 關鍵:載入檔案流
System.out.println(props.getProperty("jdbc.driver"));
System.out.println(props.getProperty("jdbc.url"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PropertiesDemo().testPropertiesFile();
}
}
FileNotFoundException。InputStreamReader 指定 UTF-8 讀取。com.microsoft.jdbc.sqlserver.SQLServerDriver
jdbc:microsoft:sqlserver://10.0.0.168:1433;
此範例在 Eclipse 3.0 環境測試通過。