首页 > 其他 > 详细

J2EE之ServletContext读取资源文件

时间:2016-04-02 10:40:50      阅读:278      评论:0      收藏:0      [点我收藏+]

ServletContext读取资源文件内容的方式有两种:

方法1.

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/data.properties");
	Properties pros = new Properties();
	pros.load(in);
		
	String username = pros.getProperty("username");
	String password = pros.getProperty("password");
		
	System.out.println("username = " + username);
	System.out.println("password = " + password);
}

技术分享

这里须要注意的是data.properties文件的位置在Myeclipse的src文件夹下,为啥getResourceAsStream方法传入的參数确实"/WEB-INF/classes/data.properties"

这是由于这些代码有webserver运行,当项目公布以后。data.properties文件就会被放到tomcat安装文件所在目录下。

如图:

技术分享技术分享技术分享

所以这里传入參数就解释清楚了。

方法2

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	String path = this.getServletContext().getRealPath("/WEB-INF/classes/data.properties");
	FileInputStream in = new FileInputStream(path);
	Properties pros = new Properties();
	pros.load(in);
		
		
	String username = pros.getProperty("username");
	String password = pros.getProperty("password");
		
	System.out.println("username = " + username);
	System.out.println("password = " + password);
}

这里首先通过getRealPath方法获取data.properties文件的绝对路径,然后通过FileInputStream获取文件流。

J2EE之ServletContext读取资源文件

原文:http://www.cnblogs.com/yxwkf/p/5346969.html

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