工程目录结构:
prj(工程根目录)
cn
json
classloader
GetResourceByClassAndClassLoader.Java
beans.xml
/**
*
*/
package cn.json.classloader;import java.io.InputStream;
/**
* @author json
*
* @date 2014-5-7
*
* @version 1.0
*/
public class GetResourceByClassAndClassLoader {/**
* class 获取资源是相对于当前class所在路径去获取
*
* classloader 是相对于classpath去获取相应的资源,采用绝对路径
*
* @param args
*/
public static void main(String[] args) {
GetResourceByClassAndClassLoader bean = new GetResourceByClassAndClassLoader();
InputStream is = bean.getClass().getResourceAsStream("../../../beans.xml");
if (is == null) {
System.out.println("resources not found!");
}
is = null;
is = bean.getClass().getResourceAsStream("/beans.xml");
if (is == null) {
System.out.println("resources not found!");
}
is = null;
is = bean.getClass().getClassLoader().getResourceAsStream("beans.xml");
if (is == null) {
System.out.println("resources not found!");
}
}
}
class getResourceAsStream 和 classloader
getResourceAsStream获取资源的不同