我是靠谱客的博主 忧心白昼,这篇文章主要介绍Servlet学习总结(8)----读取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();
        }
    }

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();
        }
    }

最后

以上就是忧心白昼最近收集整理的关于Servlet学习总结(8)----读取ClassPath下的资源文件的全部内容,更多相关Servlet学习总结(8)----读取ClassPath下内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部