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 ...
随机推荐
- win7删除桌面文件需要刷新才会消失(2种解决方法)
有没有遇到过这种情况,删除桌面文件没有效果,要点右键的刷新删除过的文件才会在桌面上消失!解决方法有两种: 第一种方法 点击"开始→运行",在对话框中输入"regedit& ...
- poj3308 Paratroopers --- 最小点权覆盖->最小割
题目是一个非常明显的二分图带权匹配模型, 加入源点到nx建边,ny到汇点建边,(nx.ny)=inf建边.求最小割既得最小点权覆盖. 在本题中因为求的是乘积,所以先所有取log转换为加法,最后再乘方回 ...
- 再造 “手机QQ” 侧滑菜单(一)——实现侧滑效果
本系列文章中,我们将尝试再造手机QQ的侧滑菜单,力争最大限度接近手Q的实际效果,并使用 Auto Layout 仿造左侧菜单,实现和主视图的联动. 代码示例:https://github.com/jo ...
- FineReport实现Java报表主题分析的效果图
Java报表-財务主题-EVA经济附加 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmVzdF9yZXBvcnQ=/font/5a6L5L2T/font ...
- stm32之CAN总线基础
can总线协议概述: CAN是Controller Area Network的缩写,由德国博世公司开发:CAN通过ISO11891以及ISO11519进行了标准化: CAN总线的特点: 1.多 ...
- nginx 解决400 bad request 的方法
nginx的400错误比较难查找原因,因为此错误并不是每次都会出现的,另外,出现错误的时候,通常在浏览器和日志里看不到任何有关提示. 经长时间观察和大量试验查明,此乃request header过大所 ...
- C语言中 移位操作运算
移位规律: 左移时总是移位和补零.右移时无符号数是移位和补零,此时称为逻辑右移;而有符号数大多数情况下是移位后补最左边的位(也就是补最高有效位),移几位就补几位,此时称为算术右移.(其实跟扩展逻辑一样 ...
- 修改VISUAL STUDIO EXPRESS 2012新建C++文件编码
本站文章除注明转载外,均为本站原创或者翻译. 本站文章欢迎各种形式的转载,但请18岁以上的转载者注明文章出处,尊重我的劳动,也尊重你的智商: 本站部分原创和翻译文章提供markdown格式源码,欢迎使 ...
- MySQL如何查询LINESTRING数据
我有一个提交的命名crm_geo_org,具有以下结构 ipoid INTEGER 11 NOT NULL PRIMARY KEY beginip INTEGER 14 NOT NULL UNSIGN ...
- 动态Pivot(1)
原文 http://book.51cto.com/art/200710/58874.htm 7.7 动态Pivot 作为另外一个练习,假设你要编写一个存储过程,它生成动态Pivot查询.这个存储过程 ...