当前位置:   article > 正文

Servlet学习总结(8)----读取ClassPath下的资源文件_servlet classpath

servlet classpath

1、如何去读取src下的资源文件?

1、依赖于ServletContext来读取:

public void init(ServletConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();

        //读取文件内容,下面的第一个/代表项目的根目录
        InputStream is = sc.getResourceAsStream("/WEB-INF/classes/test.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
            System.out.println(pro.getProperty("key"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2、使用类加载器来读取

public void init(ServletConfig config) throws ServletException {
        //类加载器读取src下的文件,不依赖于ServletContext
        InputStream is = this.getClass().getClassLoader(). .getResourceAsStream("/WEB-INF/test.properties");
        Properties pro = new Properties();
        try {
            pro.load(is);
            System.out.println(pro.getProperty("key"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/1004803
推荐阅读
相关标签
  

闽ICP备14008679号