正确使用Class.getResourceAsStream("")与Class.getClassLoader().getResourceAsStream("")

方法getResourceAsStream("")与getResource("")均常被用于获取编译路径下指定的配置文件,用法相似,下面以getResource("")为例展示其正确用法:

	/**
	 * 无package
	 */
	System.out.println(this.getClass().getResource("template.xml").getPath());//相对当前Class路径下的template.xml
	System.out.println(this.getClass().getResource("/template.xml").getPath());//classpath根路径下的template.xml
	System.out.println(this.getClass().getClassLoader().getResource("template.xml").getPath());//classpath根路径下的template.xml
	/**
	 * package
	 */
	System.out.println(this.getClass().getResource("package/template.xml").getPath());//相对当前Class路径/package路径下的template.xml
	System.out.println(this.getClass().getResource("/package/template.xml").getPath());//classpath根路径/package路径下的template.xml
	System.out.println(this.getClass().getClassLoader().getResource("package/template.xml").getPath());//classpath根路径/package路径下的template.xml
		

错误用法(注意斜杠):

	/**
	 * 无package
	 */
	System.out.println(this.getClass().getClassLoader().getResource("/template.xml").getPath());//classpath根路径下的template.xml
	/**
	 * package
	 */
	System.out.println(this.getClass().getClassLoader().getResource("/package/template.xml").getPath());//classpath根路径/package路径下的template.xml
		

注意:在Jar包中获取配置文件时,建议通过getResourceAsStream("")的方式编码。

JAVA基础普及:

Classloader 类加载器,用来加载 Java 类到 Java 虚拟机中。与普通程序不同的是。Java程序(class文件)并不是本地的可执行程序。当运行Java程序时,首先运行JVM(Java虚拟机),然后再把Java class加载到JVM里头运行,负责加载Java class的这部分就叫做Class Loader。

JVM本身包含了一个ClassLoader称为Bootstrap ClassLoader,和JVM一样,BootstrapClassLoader是用本地代码实现的,它负责加载核心JavaClass(即所有java.*开头的类)。另外JVM还会提供两个ClassLoader,它们都是用Java语言编写的,由BootstrapClassLoader加载;其中Extension ClassLoader负责加载扩展的Javaclass(例如所有javax.*开头的类和存放在JRE的ext目录下的类),ApplicationClassLoader负责加载应用程序自身的类。

当运行一个程序的时候,JVM启动,运行bootstrapclassloader,该ClassLoader加载java核心API(ExtClassLoader和AppClassLoader也在此时被加载),然后调用ExtClassLoader加载扩展API,最后AppClassLoader加载CLASSPATH目录下定义的Class,这就是一个程序最基本的加载流程。

Best Wishes For You!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值