两者不同是Class的getResource()方法是从当前.class文件路径查找资源,ClassLoader则是从jar包根目录查找.
注意:针对WEB的javaEE项目和javaSE项目,路径也是有所不同的。
下面是代码的例子,注意"/"的使用
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