J2EE之ServletContext读取资源文件

J2EE之ServletContext读取资源文件

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

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


J2EE之ServletContext读取资源文件

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

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

如图:

J2EE之ServletContext读取资源文件J2EE之ServletContext读取资源文件J2EE之ServletContext读取资源文件

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

方法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获取文件流。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号