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下内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复