Class.getResource与Class.getClassLoader.getResource

本文深入解析了Java中Class类和ClassLoader类加载资源的方式和区别,通过实例代码展示了如何在不同场景下利用这两种方式获取资源,并解释了它们在Web Java EE项目和Java SE项目中的路径差异。
这两个getResource()是使用当前ClassLoader加载资源(即资源在 Class path中),这样资源和class直接打在jar包中,避免文件路径问题.
两者不同是Class的getResource()方法是从当前.class文件路径查找资源,ClassLoader则是从jar包根目录查找.
注意:针对WEB的javaEE项目和javaSE项目,路径也是有所不同的。
下面是代码的例子,注意"/"的使用
[img]http://dl2.iteye.com/upload/attachment/0092/1832/9aa02344-fb61-3490-b8db-6d1568c81e04.jpg[/img]


package com.chinaso.phl;

/**
* @author piaohailin
* @date 2013-12-16
*/
public class Main {

public static void main(String[] args) {
System.out.println(Main.class.getResource("a.txt"));
System.out.println(Main.class.getResource("/a.txt"));
System.out.println(Main.class.getResource("/"));
System.out.println(Main.class.getResource("b.txt"));
// need to add resource/b.txt to build path! it will be package in jar file
System.out.println(Main.class.getClassLoader().getResource("b.txt"));
System.out.println(Main.class.getClassLoader().getResource("/"));
System.out.println(Thread.currentThread().getContextClassLoader().getResource("b.txt"));
}
}


eclipse中的输出结果
file:/I:/project/eclipse3.6/java.getResource/bin/com/chinaso/phl/a.txt
null
file:/I:/project/eclipse3.6/java.getResource/bin/
null
file:/I:/project/eclipse3.6/java.getResource/bin/b.txt
null
file:/I:/project/eclipse3.6/java.getResource/bin/b.txt


打包以后输出的结果
C:\my>java -classpath my.jar;b.txt com.chinaso.phl.Main
jar:file:/C:/my/my.jar!/com/chinaso/phl/a.txt
null
null
null
jar:file:/C:/my/my.jar!/b.txt
null
jar:file:/C:/my/my.jar!/b.txt


参考文章
http://www.diyhi.net/bbs/thread-436-1-1.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值