读取web应用下的资源文件(例如properties)

 1 package gz.itcast.b_resource;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.util.Properties;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 /**
12  * 读取web应用下的资源文件(例如properties)
13  * @author APPle
14  */
15 public class ResourceDemo extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19         /**
20          *  . 代表java命令运行目录。java运行命令在哪里?? 在tomcat/bin目录下
21          *   结论: 在web项目中, . 代表在tomcat/bin目录下开始,所以不能使用这种相对路径。
22          */
23         
24         
25         //读取文件。在web项目下不要这样读取。因为.表示在tomcat/bin目录下
26         /*File file = new File("./src/db.properties");
27         FileInputStream in = new FileInputStream(file);*/
28         
29         /**
30          * 使用web应用下加载资源文件的方法
31          */
32         /**
33          * 1. getRealPath读取,返回资源文件的绝对路径
34          */
35         /*String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
36         System.out.println(path);
37         File file = new File(path);
38         FileInputStream in = new FileInputStream(file);*/
39         
40         /**
41          * 2. getResourceAsStream() 得到资源文件,返回的是输入流
42          */
43         InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
44         
45         
46         Properties prop = new Properties();
47         //读取资源文件
48         prop.load(in);
49         
50         String user = prop.getProperty("user");
51         String password = prop.getProperty("password");
52         System.out.println("user="+user);
53         System.out.println("password="+password);
54         
55     }
56 
57 }
原文地址:https://www.cnblogs.com/Michael2397/p/6059317.html