首页 > 其他 > 详细

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

时间:2018-04-17 20:48:15      阅读:234      评论:0      收藏:0      [点我收藏+]
如果以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"));

}

}`
技术分享图片

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

结果:
技术分享图片

第二种方法:

类加载器只能加载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获取文件内容路径学习笔记

原文:http://blog.51cto.com/357712148/2104563

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!