使用ServletContext可以读取文件的内容,使用getResourcesAsStream()方法,运行结果会返回InputStream实例。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
ServletContext servletContext=this.getServletContext();
/**
* 读取web下面的文件
* InputStream inputStream=servletContext.getResourceAsStream("dbInfo.properties");
*/
/**
* 读取WEB-INF下面的文件
* InputStream inputStream=servletContext.getResourceAsStream("/WEB-INF/dbInfo.properties");
*/
/**
* 如果要读取的文件放在src的目录下,需要使用类加载器,如果在包下,则需要带包名
* InputStream inputStream=this.getClass().getClassLoader().getResourceAsStream("dbInfo.properties");
*/
InputStream inputStream=ContextServlet.class.getClassLoader().getResourceAsStream("com/sky/test/dbInfo.properties");
//属性配置文件
Properties pp=new Properties();
pp.load(inputStream);
out.println(pp.getProperty("name"));
}
本文介绍了如何在Java Web开发中,通过ServletContext对象的getResourcesAsStream()方法读取项目中的配置文件,从而获取InputStream实例,实现对配置文件内容的访问。
1249

被折叠的 条评论
为什么被折叠?



