首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >J2EE之ServletContext读取资源文件

J2EE之ServletContext读取资源文件

作者头像
全栈程序员站长
发布2022-07-10 13:18:05
发布2022-07-10 13:18:05
3800
举报

大家好,又见面了,我是全栈君。

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

方法1.

代码语言:javascript
复制
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

代码语言:javascript
复制
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获取文件流。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/115509.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年2月3,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档