读取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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值