Servlet之ServletContext读取web应用中的资源文件

1.Servlet读取

<span style="font-family:KaiTi_GB2312;font-size:14px;">//ServletContext读取web应用中的资源文件
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
	// 读取资源文件,最好采用ServletContext去读
	InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
	this.getServletConfig().getServletContext();
	//或是采用如下,通过ServletContext的getRealPath获取资源的绝对路径,在通过传统读取,这样可以获取资源名称
	//String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
	//String fileName = path.subString(path.lastIndexOf("\\")+1);//资源名称,这种方法会在下载时用到。
	//FileInputStream in = new FileInputStream(path);

	// 这里读取数据采用的是相对路径。
<span style="white-space:pre">	</span>// 这行代码是由服务器调用,所以此处的相对路径是C:\Program Files\Apache Software\Foundation\Tomcat 6.0\bin
	// 需要在这个目录下建立classes/db.properties才能读取到
	// InputStream in = new FileInputStream("classes/db.properties");
	Properties props = new Properties();
	props.load(in);// 继承自HashTable,但是这个方法是扩展的
	System.out.println(props.getProperty("url"));
}</span>

2.普通类读取

<span style="font-family:KaiTi_GB2312;font-size:14px;">// 如果读取资源文件的程序不是Servlet的话,就只能通过类装载器去读,但要注意,读取的文件不能太大,否则,内存崩了
// 注意:这里是采用类装载器的方式,假如改了db.properties文件,那么读取时,类装器发现已经有了,就不读了。
// 当然这里采取的是静态代码块,更是只加载一次了
// 可以读取文件,但是无法读取更新后的
// private static Properties dbConfig = new Properties();
<span style="white-space:pre">	</span>// static{
<span style="white-space:pre">	</span>// try{
<span style="white-space:pre">	</span>// InputStream in =
	// CommonWebSource.class.getClassLoader().getResourceAsStream("db.properties");
	// dbConfig.load(in);
	// }catch(Exception e){
	// throw new ExceptionInInitializerError(e);
	// }
	// }

//这里只是通过类装载器拿出了路径(类似取出属性一样),并没有做任何装载操作,可以读到更新后的
public void update() throws IOException {
	String path = CommonWebSource.class.getClassLoader().getResource("db.properties").getPath();
	InputStream in = new FileInputStream(path);

	Properties props = new Properties();
	props.load(in);
	System.out.println(props.getProperty("url"));
}</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值