路徑名中"." 代表是當(dāng)前路徑峡捡,相當(dāng)于java命令運(yùn)行的目錄
運(yùn)行web項(xiàng)目時(shí)," . "即代表Tomcat/bin目錄下開始,所以不能使用這種相對(duì)路徑
一般在web應(yīng)用下讀取資源文件通過如下2種方式
/**
* 1. getRealPath讀取,返回資源文件的絕對(duì)路徑
*/
String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
System.out.println(path);
File file = new File(path);
FileInputStream in = new FileInputStream(file);
/**
* 2. getResourceAsStream() 得到資源文件,返回的是輸入流
*/
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop = new Properties();
//讀取資源文件
prop.load(in);
String user = prop.getProperty("user");
String password = prop.getProperty("password");
System.out.println("user="+user);
System.out.println("password="+password);