码迷,mamicode.com
首页 > 编程语言 > 详细

Java中获取资源文件的方法总结

时间:2017-06-03 10:02:44      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:方法   根目录   response   ext.get   images   pat   content   input   source   

这里总结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/>");
	}

  得到结果:

技术分享

 

Java中获取资源文件的方法总结

标签:方法   根目录   response   ext.get   images   pat   content   input   source   

原文地址:http://www.cnblogs.com/zydev/p/6935715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!