Servlet获取类路径下的资源

示例程序:

 1 package cn.yzu;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import org.apache.commons.io.IOUtils;
 9 public class AServlet extends HttpServlet {
10 
11     public void doGet(HttpServletRequest request, HttpServletResponse response)
12             throws ServletException, IOException {
13         ClassLoader loader=this.getClass().getClassLoader();
14         //相对于TOMCAT中classes目录
15         InputStream stream=loader.getResourceAsStream("cn/yzu/A");
16         InputStream stream2=loader.getResourceAsStream("../../index.jsp");
17         //IO小工具,将输入流转换成字符串
18         String s=IOUtils.toString(stream);
19         System.out.println(s);
20         System.out.println("---------------------------------------------------");
21         System.out.println(IOUtils.toString(stream2));
22     }
23     public void doPost(HttpServletRequest request, HttpServletResponse response)
24             throws ServletException, IOException {
25         doGet(request, response);
26     }
27 }
View Code

运行结果:

注:IO小工具所用jar包:(APACHE提供,可到官网下载)

 

posted @ 2016-10-23 11:28  凌晨。。。三点  阅读(232)  评论(0编辑  收藏  举报