ServletContex获取文件内容路径学习笔记

本文介绍了两种在Java Web应用中读取资源文件的方法:一是使用ServletContext获取资源流,适用于读取位于web应用目录下的文件;二是利用类加载器加载资源,适合加载位于/WEB-INF/classes/目录下的文件。

如果以ServletContext方式读取资源文件(txt/xml/properties),是相对于web服务器的当前web应用目录而言
此时/表示:当前web应用

第一种方法

    `import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Emaldome4 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

       ServletContext context = this.getServletContext();   
       InputStream is = context.getResourceAsStream("/res/config.properties");
       Properties props = new Properties();
       props.load(is);
       System.out.println(props.getProperty("email"));

}

}`
ServletContex获取文件内容路径学习笔记

访问:
http://localhost:8080/day04/Emaldome4

结果:
ServletContex获取文件内容路径学习笔记

第二种方法:

类加载器只能加载IDE工具下src目录下的资源文件,其它目录无法加载
此时/表示:/WEB-INF/classes/目录


           //通过类加载器加载src/config.properteis资源文件
           //取得当前对象的字节码对象
            Class clazz =   this.getClass();
            //取得当前对象的类加载器
            ClassLoader cl =  clazz.getClassLoader();

            //
            InputStream is =  cl.getResourceAsStream("/cn/config/config.properties");

            Properties props = new Properties();
            props.load(is);
            System.out.println(props.getProperty("email"));

ServletContex获取文件内容路径学习笔记

转载于:https://blog.51cto.com/357712148/2104563

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值