Project获取资源需要一个启点,加载资源的动作是由ClassLoader来完成的。Class对象和当前线程对象可以找到当前加载资源的ClassLoader,通过ClassLoader的getResource(String name)方法及其它衍生出来的方法可以找到Application的启点及获取相关资源
private void display() {path=this.getClass().getResource("/loadresource").getPath();System.out.println(path);path=this.getClass().getResource("/loadresource/bp.txt").getPath();System.out.println(path);path=this.getClass().getResource("/").getPath();System.out.println(path);URL url=this.getClass().getResource("loadresource/bp.txt");System.out.println("Is Null:"+(url==null));path=GetResouceTest.class.getClassLoader().getResource("").getPath();System.out.println(path);path=GetResouceTest.class.getClassLoader().getResource("loadresource/bp.txt").getPath();System.out.println(path);url=GetResouceTest.class.getClassLoader().getResource("/loadresource/bp.txt");System.out.println("Is Null:"+(url==null));path=Thread.currentThread().getContextClassLoader().getResource("").getPath();System.out.println(path);path=Thread.currentThread().getContextClassLoader().getResource("loadresource/bp.txt").getPath();System.out.println(path);url=Thread.currentThread().getContextClassLoader().getResource("loadresource/bp.txt");System.out.println("Is Null:"+(url==null));url=Thread.currentThread().getContextClassLoader().getResource("/loadresource/bp.txt");System.out.println("Is Null:"+(url==null));}

Output:

/E:/java/workspace/test/bin/loadresource
/E:/java/workspace/test/bin/loadresource/bp.txt
/E:/java/workspace/test/bin/
Is Null:true
/E:/java/workspace/test/bin/
/E:/java/workspace/test/bin/loadresource/bp.txt
Is Null:true
/E:/java/workspace/test/bin/
/E:/java/workspace/test/bin/loadresource/bp.txt
Is Null:false
Is Null:true

Conclusion:
java.lang.Class<T>的URL  getResource(String name)时可以使用参数:
(1)"/":代表项目根目录,也就是ClassPath的root

(2)以"/"开头的包路径

java.lang.ClassLoader的URL getResource(String name)时使用参数:
(1)"":代表项目根目录,也就是ClassPath的root
(2)不以"/"开头的包路径

源码解析:

java.lang.Class

 /*** Finds a resource with a given name.  The rules for searching resources* associated with a given class are implemented by the defining* {@linkplain ClassLoader class loader} of the class.  This method* delegates to this object's class loader.  If this object was loaded by* the bootstrap class loader, the method delegates to {@link* ClassLoader#getSystemResource}.** <p> Before delegation, an absolute resource name is constructed from the* given resource name using this algorithm:** <ul>** <li> If the {@code name} begins with a {@code '/'}* (<tt>'\u002f'</tt>), then the absolute name of the resource is the* portion of the {@code name} following the {@code '/'}.** <li> Otherwise, the absolute name is of the following form:** <blockquote>*   {@code modified_package_name/name}* </blockquote>** <p> Where the {@code modified_package_name} is the package name of this* object with {@code '/'} substituted for {@code '.'}* (<tt>'\u002e'</tt>).** </ul>** @param  name name of the desired resource* @return      A  {@link java.net.URL} object or {@code null} if no*              resource with this name is found* @since  JDK1.1*/public java.net.URL getResource(String name) {name = resolveName(name);ClassLoader cl = getClassLoader0();if (cl==null) {// A system class.return ClassLoader.getSystemResource(name);}return cl.getResource(name);}

   /*** Add a package name prefix if the name is not absolute Remove leading "/"* if name is absolute*/private String resolveName(String name) {if (name == null) {return name;}if (!name.startsWith("/")) {Class<?> c = this;while (c.isArray()) {c = c.getComponentType();}String baseName = c.getName();int index = baseName.lastIndexOf('.');if (index != -1) {name = baseName.substring(0, index).replace('.', '/')+"/"+name;}} else {name = name.substring(1);
        }return name;}

从源码看:
(1)java.lang.Class的getResource(String name)方法调用了ClassLoader的getResource(String name)方法;

(2)java.lang.Class的resolveName(String name)方法去掉了name中的第一个字符“/”,

java.lang.Classloader的getResource(String name)的参数name首字母没有“/”

Extension section:

如果路径中有空格及中文在某些场景会出来问题。

可以尝试在getResource(Sting name).toURL()来解决。

http://www.cnblogs.com/softidea/p/3888829.html

getResource(String name)用法及源码分析相关推荐

  1. 一文了解 lambda 用法与源码分析

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 来源 | cmlanche.com/2018/07/22 ...

  2. 你真的了解lambda吗?一文让你明白lambda用法与源码分析

    本文作者: cmlanche 本文链接: http://www.cmlanche.com/2018/07/22/lambda用法与源码分析/ 转载来源:cmlanche.com 用法 示例:最普遍的一 ...

  3. Jetpack-LiveData用法与源码分析

    LiveData用法与源码分析 LiveData定义和作用 LiveData用法 LiveData源码分析 Observe setValue和postValue 总结 数据粘性(倒灌)分析 LiveD ...

  4. 【Android 异步操作】Timer 定时器 ( Timer 与 TimerTask 基本使用 | Timer 定时器常用用法 | Timer 源码分析 )

    文章目录 一.Timer 定时器基本使用 二.Timer 定时器常用用法 三.Timer 源码分析 四.Timer 部分源码注释 五.源码及资源下载 参考文档 : Timer 定时器 API 文档 T ...

  5. Android研发中对String的思考(源码分析)

    1.常用创建方式思考: String text = "this is a test text "; 上面这一句话实际上是执行了三件事  1.声明变量 String text; 2. ...

  6. java 向上取整方法 Math.ceil() 用法、源码分析

    刷题用到了,正好好好看看源码. 用法 Math.ceil() 返回值.参数均为double类型, 如果参数为int类型,idea不会报错,但是方法同时不会向上取整. 参数为int类型时,Math.ce ...

  7. threadlocal用法_ThreadLocal源码分析

    java.lang.ThreadLocal类在平时的开发中很少用到,勾勾工作5年多一直没有用过.最近在学习spring源码时发现很多地方用到,并且这个类是面试高频题目,不明白为什么大厂喜欢考察这个类的 ...

  8. 高并发编程-Thread#interrupt用法及源码分析

    文章目录 官网 方法&源码 void interrupt() ` boolean isInterrupted()` vs `static boolean interrupted()` 方法&a ...

  9. java string is empty_从源码分析java.lang.String.isEmpty()

    今天在写代码的时候用到了java.lang.String.isEmpty()的这个方法,之前也用过,今天突发奇想,就看了看源码,了解了解它的实现方法,总结出来,大家可以交流交流. 通常情况下,我们使用 ...

最新文章

  1. WEB应用数据验证指南
  2. 【重要】使用Git命令行上传到GitHub上
  3. 查看并开启MySQL的log-bin和general_log日志
  4. maven找到mysql 连接池_在Tomcat6.0+MySQL5.0环境下配置和使用数据库连接池
  5. .NET Core 1.0发布:微软开源跨平台大布局序幕
  6. oracle 31640,导数据时ora-31640报错
  7. ecs服务器换系统,ecs服务器更换操作系统
  8. postman中文设置_严选 | Elastic中文社区201902错题本
  9. 基于JAVA+SpringBoot+Mybatis+MYSQL的请假与审批系统
  10. 以太局域网(以太网)
  11. paip.Adblock屏蔽规则保存位置以及修理恢复
  12. (双硬盘(SSD+HDD)/单硬盘)双系统win10+ubuntu18.04安装记录
  13. 矩阵理论 期末判断题汇总
  14. 杰理之AUDIO_DAC【篇】
  15. 爬虫爬取wallpaperswide上的高清壁纸
  16. 前端开发中PC端和移动端网站的区别
  17. 关于红帽RHCE考试的那些事儿
  18. unity3d Hair real time rendering 真实头发实时渲染
  19. 全球即将诞生第二家卡车自动驾驶上市公司,行业转折点已经到来
  20. java英语句子_经典英语句子 (转) - HelloWorld 善战者,求之于势,不责于人;故能择人而任势。 - BlogJava...

热门文章

  1. 80 after generation to marry or not to marry that is a question
  2. 计算机硬件存储器,个人计算机的存储器系统 说说内核与计算机硬件结构(5)
  3. java中do loop的使用_Java中do-while循环——通过示例学编程(11)
  4. python中使用函数的优点,对于python类使用“get函数”有什么好处?
  5. 使用Docker-数据卷命令
  6. Zookeeper的前世今生
  7. 用户注册 - 判断用户名存在
  8. SpringSecurity认证流程回顾
  9. OpenResty安装
  10. Nginx与Zuul之间区别