getResource(String name)用法及源码分析
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)用法及源码分析的更多相关文章
- 你真的了解lambda吗?一文让你明白lambda用法与源码分析
本文作者: cmlanche 本文链接: http://www.cmlanche.com/2018/07/22/lambda用法与源码分析/ 转载来源:cmlanche.com 用法 示例:最普遍的一 ...
- 你真的了解java的lambda吗?- java lambda用法与源码分析
你真的了解java的lambda吗?- java lambda用法与源码分析 转载请注明来源:cmlanche.com 用法 示例:最普遍的一个例子,执行一个线程 new Thread(() -> ...
- java String类 trim() 方法源码分析
public String trim() { int arg0 = this.value.length; //得到此字符串的长度 int arg1 = 0; //声 ...
- String、StringBuffer、StringBuilder源码分析
利用反编译具体看看"+"的过程 1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 int ...
- Spring源码分析之IOC的三种常见用法及源码实现(二)
Spring源码分析之IOC的三种常见用法及源码实现(二) 回顾上文 我们研究的是 AnnotationConfigApplicationContext annotationConfigApplica ...
- string源码分析 ——转载 http://blogs.360.cn/360cloud/2012/11/26/linux-gcc-stl-string-in-depth/
1. 问题提出 最近在我们的项目当中,出现了两次与使用string相关的问题. 1.1. 问题1:新代码引入的Bug 前一段时间有一个老项目来一个新需求,我们新增了一些代码逻辑来处理这个新需求.测试阶 ...
- ArrayList用法详解与源码分析
说明 此文章分两部分,1.ArrayList用法.2.源码分析.先用法后分析是为了以后忘了查阅起来方便-- ArrayList 基本用法 1.创建ArrayList对象 //创建默认容量的数组列表(默 ...
- 一个由正则表达式引发的血案 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. 一些特殊字符,如“&”,“- ...
- NIO 源码分析(01) NIO 最简用法
目录 一.服务端 二.客户端 NIO 源码分析(01) NIO 最简用法 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) J ...
随机推荐
- HTML5实现IP Camera网页输出
HTML5实现IP Camera网页输出 这两天做OA项目.有一个要通过IP Camera将视频流输出到浏览器端的模块.尽管如今买到的摄像头都会提供浏览器和client的实现,可是一般来说都是仅仅支持 ...
- NanShan即时通讯论——HTML5的优势与劣势
原文:NanShan即时通讯论--HTML5的优势与劣势 NanShan即时通讯 学习html时才是XHTML 1.0,接着是 HTML4.01,再到HTML5,如今HTML5 開始吸引越来越多的人的 ...
- Eclipse生成Jar包方法
Eclipse生成jar包 第一:普通类导出jar包,我说的普通类就是指此类包含main方法,并且没有用到别的jar包. 1.在eclipse中选择你要导出的类或者package,右击,选择Exp ...
- ZOJ3768 夹逼查找【STL__lower_bound()_的应用】
首先学习一下lower_bound() 函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置.如果所有元素都小于val,则返回last ...
- 在win8.1上用Bitvise SSH Server 6.24(原名winsshd)搭建SSH2服务器
注意:此SSH是指运维领域的 SSH,不是指JavaWeb框架中的SSH. 运维领域:SSH=Secure Shell安全外壳协议 JavaWeb框架:SSH=Spring+Struts+Hibern ...
- WPF4字体改善
原文 WPF4字体改善 WPF4对字体渲染做了很大的改善,增加了TextOptions属性,该属性可以设置TextFormattingMode,TextRenderingMode,TextHintin ...
- maven常见问题汇总
package阶段得到的是build目录下编译后的类包(jar),install是把这个包和一些maven的元信息(比如pom.xml)复制到本地仓库,assembly一般是把build结果和一些资源 ...
- Activity生命周期方法的调用顺序project与測试日志
以下为測试activity的方法的运行顺序 project与測试资源地址 androidproject AndroidManifest.xml <? xml version="1. ...
- PHP - 操作MySQL数据库
第16章 PHP操作MySQL 学习要点: 1.PHP连接到MySQL 2.增删改查 3.其他常用函数 如果你已经具有了使用PHP.SQL和MySQL的丰富经验,现在就可以把所有这些技术组合在一起.P ...
- VS2010对C++11的支持列表(感觉大部分都不支持)
c++11,就是之前的c++0x,已经成为了最新的c++标准.像咱这样天天用c++的,就赶紧follow一下.学习成果,放在这里,不说分享,至少自己增强下记忆. 首先,给出一些有用的链接. http: ...