讀取web專案web-inf目錄下的jdbc.properties檔案
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesRead {
/****
* 讀取根目下web-inf/config目錄下的jdbc.properties檔案
*/
private static String address="";
/***
* 從屬性檔案中讀取配置的屬性,從類第一次載入時就讀取,只讀一次
*/
static{
Properties prop = new Properties();
String path =PropertiesRead.class.getResource("/").getPath();
System.out.println(path);
//獲取web-inf目錄的路徑
path=path.substring(1, path.indexOf("build"));
System.out.println(path);
InputStream in=null;
try {
//讀去檔案
//E:\workspaseHY\HYTT\WebContent\WEB-INF\config
in =new FileInputStream(path+"WebContent/WEB-INF/config/jdbc.properties");
prop.load(in);
address = prop.getProperty("driverClassName");
System.out.println(address);
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(in!=null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}