項目結構
在 JDBC 中 DBUtil.java 加載配置文件時,路徑使用的是Java項目的相對路徑。存在本地的。
// 加載配置文件
Properties p = new Properties();
FileInputStream in = new FileInputStream("resource/db.properties");
p.load(in);
在做javaWeb的時候,路徑需要修改下:
// 加載配置文件
Properties p = new Properties();
// 獲取字節碼目錄
String path = DBUtil.class.getClassLoader().getResource("db.properties").getPath();
System.out.println(path);
// 解決路徑中 空格顯示為 %20
path = URLDecoder.decode(path, "utf-8");
System.out.println(path);
FileInputStream in = new FileInputStream(path);
p.load(in);