class.getResource()和class.getResourceAsStream()的用法

package com.lxz;

import java.io.InputStream;
import org.junit.Test;

public class FileDemo {
	@Test
	public void testFileDemo() {
		//getResourceAsStream:查找具有给定名称的资源。返回 inputstream
		//getResource:查找带有给定名称的资源路径。返回URL
		
		//在使用Class.getResourceAsStream 时,资源路径有两种方式,
		//一种以“/”开头,这样的路径是指绝对路径,如果不以“/”开头,则路径是相对于这个class所在的包的。
		//当前类com.lxz.FileDemo
		//a.txt文件的路径为E:\Workspace\MyEclipse\StudentManager\WebContent\WEB-INF\class
		InputStream absolutePath1 = this.getClass().getResourceAsStream("/a.txt");
		System.out.println(absolutePath1 == null ? "can't find file" : "file can use");		//file can use
		InputStream relativePath1 = this.getClass().getResourceAsStream("a.txt");		//相对路径,相对于当前类
		System.out.println(relativePath1 == null ? "can't find file" : "file can use");		//can't find file
		
		InputStream absolutePath2 = FileDemo.class.getResourceAsStream("/a.txt");
		System.out.println(absolutePath2 == null ? "can't find file" : "file can use");		//file can use
		InputStream relativePath2 = FileDemo.class.getResourceAsStream("a.txt");
		System.out.println(relativePath2 == null ? "can't find file" : "file can use");		//can't find file
		
		//ClassLoader的查找默认就是以classpath开始的绝对路径,不能加"/",否则会找不到文件
		InputStream absolutePath3 = ClassLoader.getSystemResourceAsStream("/a.txt");
		System.out.println(absolutePath3 == null ? "can't find file" : "file can use");		//can't find file
		InputStream relativePath3 = ClassLoader.getSystemResourceAsStream("a.txt");
		System.out.println(relativePath3 == null ? "can't find file" : "file can use");		//file can use
		
		//file:/E:/Workspace/MyEclipse/StudentManager/WebContent/WEB-INF/class/
		System.out.println(this.getClass().getClassLoader().getResource(""));
		//null
		System.out.println(this.getClass().getClassLoader().getResource("/"));
		//NullPointerException
		//System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
		
		//class com.lxz.FileDemo
		System.out.println(this.getClass());
		//class java.lang.Class
		System.out.println(this.getClass().getClass());
		class com.lxz.FileDemo
		System.out.println(FileDemo.class);
		//class java.lang.Class
		System.out.println(FileDemo.class.getClass());
		
		//a.text路径-->file:/E:/Workspace/MyEclipse/StudentManager/WebContent/WEB-INF/class/a.txt
		System.out.println("a.text路径-->" + this.getClass().getResource("/a.txt"));
		//a.text路径-->null
		System.out.println("a.text路径-->" + this.getClass().getResource("a.txt"));
		
	}
}

@SuppressWarnings("serial")
public class FileDemoServlet extends HttpServlet {
	@Override
	public void init() throws ServletException {
		//getRealPath(String str)这个方法可以动态地获得文件的路径,不必直接手写绝对路径,但这个是不被建议使用的方法
		//E:\Workspace\MyEclipse\StudentManager\WebContent\
		System.out.println(this.getServletContext().getRealPath("/"));
		//E:\Workspace\MyEclipse\StudentManager\WebContent
		System.out.println(this.getServletContext().getRealPath(""));
		
		//E:\Workspace\MyEclipse\StudentManager\WebContent\FileDemo.class
		System.out.println(this.getServletContext().getRealPath("/FileDemo.class"));
		//E:\Workspace\MyEclipse\StudentManager\WebContent\FileDemo.class
		System.out.println(this.getServletContext().getRealPath("FileDemo.class"));
		
		//E:\Workspace\MyEclipse\StudentManager\WebContent\com\lxz\FileDemo.class
		System.out.println(this.getServletContext().getRealPath("com/lxz/FileDemo.class"));
		//E:\Workspace\MyEclipse\StudentManager\WebContent\com\lxz\FileDemo.class
		System.out.println(this.getServletContext().getRealPath("/com/lxz/FileDemo.class"));
		
		//不存在的目录和文件
		//E:\Workspace\MyEclipse\StudentManager\WebContent\nonExistent\nonExistentFile.class
		System.out.println(this.getServletContext().getRealPath("/nonExistent/nonExistentFile.class"));
		//E:\Workspace\MyEclipse\StudentManager\WebContent\nonExistent\nonExistentFile.class
		System.out.println(this.getServletContext().getRealPath("nonExistent/nonExistentFile.class"));
		
		System.out.println(this.getServletConfig().getInitParameterNames());
		Enumeration<String> param = this.getServletConfig().getInitParameterNames();
		if(param.hasMoreElements()){
			System.out.println("初始化参数-->" + param.nextElement());
		}
		
		//1.在整个Servlet的生命周期中init方法仅被调用一次
        //2.用户定义的Servlet中可以覆盖有参或无参的init方法,但是若覆盖有参init方法,最好先调用super.init(config),
		//对变量config进行赋值初始化。而覆盖无参init可以不调用super.init(),推荐覆盖无参init,为了使用方便。
        //3.用户定义的Servlet中可以不去覆盖init方法,覆盖只是为了使用方便,如:获得web.xml中描述的初始化参数。
		
		//servlet初始化参数的使用非常依赖于部署描述文件(web.xml),该文件可存放servlet所需要的起始参数
		//以及web应用程序的结构数据。当servlet容器读取web.xml文件内容后。可以将这些起始参数封装成一个对象
		//并在调用init方法时传递给servlet,这个对象就是ServletConfig对象。所以我们可以在Servlet内覆写init方法,
		//并通过ServletCongig对象来取得某些初始参数。
	}
	@Override
	public void init(ServletConfig config) throws ServletException {
		//会比init()方法先调用
		System.out.println("被调用");
		super.init(config);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		out.print("当前时间为-->" + new Date());
		//输出项目名/StudentManager
		System.out.println(req.getContextPath());
	}
}

public class Test {
	@org.junit.Test
	public void test(){
		/*
	 	ClassLoader提供了两个方法用于从装载类路径中取得资源:
		public URL getResource(String name);  
		public InputStream getResourceAsStream(String name);  
	
		这里name是资源的类路径,它是相对与“/”根路径下的位置。
		getResource得到的是一个URL对象来定位资源,而getResourceAsStream获得
		该资源输入流的引用,保证程序可以从正确的位置获取数据。
		但是真正使用的不是ClassLoader的这两个方法,而是Class的 getResource和getResourceAsStream方法,
		因为Class对象可以从你的类得到(如YourClass.class或 YourClass.getClass()),
		而ClassLoader则需要再调用一次YourClass.getClassLoader()方法,不过根据JDK文档的说法,
		Class对象的这两个方法其实是“委托”(delegate)给装载它的ClassLoader来做的,
		所以只需要使用 Class对象的这两个方法就可以了。
		因此,直接调用  this.getClass().getResourceAsStream(String name)获取流,
		静态化方法中则使用ClassLoader.getSystemResourceAsStream (String name) ; 。
		 */
		//file:/E:/Workspace/MyEclipse/StudentManager/WebContent/WEB-INF/class/com/lxz/
		System.out.println(this.getClass().getResource(""));
		//file:/E:/Workspace/MyEclipse/StudentManager/WebContent/WEB-INF/class/
		System.out.println(this.getClass().getClassLoader().getResource(""));
		
		String userDir = System.getProperty("user.dir");
		String userHome = System.getProperty("user.home");
		//userDir-->E:\Workspace\MyEclipse\StudentManager
		//userHome-->C:\Users\Lu
		System.out.println("userDir-->" + userDir);
		System.out.println("userHome-->" + userHome);
	}
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值