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吗?一文让你明白lambda用法与源码分析

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

  2. 你真的了解java的lambda吗?- java lambda用法与源码分析

    你真的了解java的lambda吗?- java lambda用法与源码分析 转载请注明来源:cmlanche.com 用法 示例:最普遍的一个例子,执行一个线程 new Thread(() -> ...

  3. java String类 trim() 方法源码分析

    public String trim() {        int arg0 = this.value.length;   //得到此字符串的长度        int arg1 = 0;   //声 ...

  4. String、StringBuffer、StringBuilder源码分析

    利用反编译具体看看"+"的过程 1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 int ...

  5. Spring源码分析之IOC的三种常见用法及源码实现(二)

    Spring源码分析之IOC的三种常见用法及源码实现(二) 回顾上文 我们研究的是 AnnotationConfigApplicationContext annotationConfigApplica ...

  6. string源码分析 ——转载 http://blogs.360.cn/360cloud/2012/11/26/linux-gcc-stl-string-in-depth/

    1. 问题提出 最近在我们的项目当中,出现了两次与使用string相关的问题. 1.1. 问题1:新代码引入的Bug 前一段时间有一个老项目来一个新需求,我们新增了一些代码逻辑来处理这个新需求.测试阶 ...

  7. ArrayList用法详解与源码分析

    说明 此文章分两部分,1.ArrayList用法.2.源码分析.先用法后分析是为了以后忘了查阅起来方便-- ArrayList 基本用法 1.创建ArrayList对象 //创建默认容量的数组列表(默 ...

  8. 一个由正则表达式引发的血案 vs2017使用rdlc实现批量打印 vs2017使用rdlc [asp.net core 源码分析] 01 - Session SignalR sql for xml path用法 MemCahe C# 操作Excel图形——绘制、读取、隐藏、删除图形 IOC,DIP,DI,IoC容器

    1. 血案由来 近期我在为Lazada卖家中心做一个自助注册的项目,其中的shop name校验规则较为复杂,要求:1. 英文字母大小写2. 数字3. 越南文4. 一些特殊字符,如“&”,“- ...

  9. NIO 源码分析(01) NIO 最简用法

    目录 一.服务端 二.客户端 NIO 源码分析(01) NIO 最简用法 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) J ...

随机推荐

  1. Ganglia 权威指南-安装Ganglia过程

    转自于:http://blog.csdn.net/xxd851116/article/details/21527055 http://www.dataguru.cn/article-3816-1.ht ...

  2. DHCP的工作原理

    什么是dhcp?它是如何实现的? DHCP称为动态主机配置协议.DHCP服务允许工作站连接到网络并且自动获取一个IP地址.配置DHCP服务的服务器可以为每一个网络客户提供一个IP地址.子网掩码.缺省网 ...

  3. struts+hibernate 请求数据库增删改查(小项目实例)

      StudentAction.java package com.action; import java.util.ArrayList; import java.util.List; import j ...

  4. 7款Linux下阅读PDF的阅读器。

    5款Linux下阅读PDF的阅读器.1. Mupdf:link 2. Adobe Reader:link 3. Foxit Reader:link 4.Evince:link 5. Okular:li ...

  5. NOI2007 生成树计数

    题目 首先我要吐槽,这题目就是坑,给那么多无用的信息,我还以为要根据提示才能做出来呢! 算法1 暴力,傻傻地跟着提示,纯暴力\(40\)分,高斯消元\(60\)分. 算法2 DP!一个显然的东西是,这 ...

  6. android Context的理解

    很多初入Android开发的网友向我们问到Context有什么作用,很多地方都用到它,这里Android123给这些新入门的网友做个简单的解释:  Context字面意思上下文,位于framework ...

  7. c++, class的大小

    不为类.对象的函数分配空间: 在类中如果有virtual声明的虚函数,则会隐藏一个指针,该指针指向虚函数表,这对于纯虚函数也是一样: 对于虚继承,还有一个指向父类的指针,该指针为指向虚基类的指针(Po ...

  8. UVa 11045 My T-shirt suits me / 二分图

    二分图建图 判断是否是完全匹配就行 最大流也行 #include <cstdio> #include <cstring> const int MAX = 300; int a[ ...

  9. Linux下安装配置词典GoldenDict

    GoldenDict   apt-get install goldendict 安装完成以后,需要自己手动加入字典,增加在线翻译网址(例如,有道,金山等),点击 编辑--dictionaries  完 ...

  10. c#实现Javascript的encodeURIComponent()函数

    原文  c#实现Javascript的encodeURIComponent()函数 国内外各搜索引擎,均用JavaScript的encodeURIComponent()函数对搜索关键字进行编码,终于找 ...