这里总结3中方法获取资源文件的
- ServletContext
- Class
- ClassLoader
文件的位置
1. ServletContext
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); ServletContext context = this.getServletContext(); /** * 获取不同路径下的资源文件 * servletContext是相对于项目的根目录的,这里为WebContent */ InputStream inputA = context.getResourceAsStream("/a.txt"); InputStream inputB = context.getResourceAsStream("/WEB-INF/classes/cn/zydev/b.txt"); InputStream inputC = context.getResourceAsStream("/WEB-INF/classes/c.txt"); /** * 获取真实的磁盘路径 */ String realPath = context.getRealPath("/WEB-INF/classes/c.txt"); /** * 获取指定目录下的文件(包括目录,深度为1级) */ Set<String> rsc = context.getResourcePaths("/WEB-INF"); String a = IOUtils.toString(inputA); String b = IOUtils.toString(inputB); String c = IOUtils.toString(inputC); pw.print(a+"<br/>"); pw.print(b+"<br/>"); pw.print(c+"<br/>"); pw.print(realPath+"<br/>"); pw.println(rsc); }
结果显示:
2. ClassLoader
使用ClassLoader是相对于classes的
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); /** * ClassLoader是相对于classes参照的 * 第一个斜杠可以不写,也可以写成./(熟悉Linux的应该很清楚) */ ClassLoader cl = this.getClass().getClassLoader(); InputStream inputA = cl.getResourceAsStream("/../../a.txt"); InputStream inputB = cl.getResourceAsStream("/cn/zydev/b.txt"); InputStream inputC = cl.getResourceAsStream("/c.txt"); String a = IOUtils.toString(inputA); String b = IOUtils.toString(inputB); String c = IOUtils.toString(inputC); pw.print(a+"<br/>"); pw.print(b+"<br/>"); pw.print(c+"<br/>"); }
得到结果:
3. class
路径前斜杠表示相对于当前的class,不加斜杠相对于classes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); Class cs = this.getClass(); //不加斜杠表示相对于class(CServlet) InputStream inputA = cs.getResourceAsStream("../../../../a.txt"); InputStream inputB = cs.getResourceAsStream("b.txt"); //加斜杠,相对于classes InputStream inputC = cs.getResourceAsStream("/c.txt"); String a = IOUtils.toString(inputA); String b = IOUtils.toString(inputB); String c = IOUtils.toString(inputC); pw.print(a+"<br/>"); pw.print(b+"<br/>"); pw.print(c+"<br/>"); }
得到结果:
时间: 2024-10-12 13:06:30