路径名中"." 代表是当前路径,相当于java命令运行的目录
运行web项目时," . "即代表Tomcat/bin目录下开始,所以不能使用这种相对路径
一般在web应用下读取资源文件通过如下2种方式
/**
* 1. getRealPath读取,返回资源文件的绝对路径
*/
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);
网友评论