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 ...
随机推荐
- WinDbg分析DUMP文件
1. 如何生成dump文件? 原理:通过SetUnhandledExceptionFilter设置捕获dump的入口,然后通过MiniDumpWriteDump生成dump文件: ...
- BZOJ 3477: [Usaco2014 Mar]Sabotage( 二分答案 )
先二分答案m, 然后对于原序列 A[i] = A[i] - m, 然后O(n)找最大连续子序列和, 那么此时序列由 L + mx + R组成. L + mx + R = sum - n * m, s ...
- OAuth2.0认证过程
本文以腾讯微博为例,详细介绍OAuth2.0的认证过程. 在使用腾讯微博平台提供的API前,您需要做以下两步工作: 成为开发者,并申请appkey和appsecret 授权获取accesstoken ...
- char、signed char 和 unsigned char 的区别
ANSI C 提供了3种字符类型,分别是char.signed char.unsigned char.而不是像short.int一样只有两种(int默认就是signed int). 三者都占1个字节( ...
- 基于visual Studio2013解决C语言竞赛题之0610冒泡排序函数
题目
- Windows的TCP协议参数
注册表编辑器:regedit 表项:HKEY_LOCAL_MACHINE\SYSTEM\CurentControlSet\Services\Tcpip\Parameters 窗口扩大因子 & ...
- 基于visual Studio2013解决C语言竞赛题之1037数组求列和
题目 解决代码及点评 /* 功能:已知有三个数组A,B,C,A为5行5列的二维数组,B.C为只有5个元素的一维数组,键盘输入数据的顺序如下: 23,45,6,1,- ...
- boost ini
#include <boost/property_tree/ptree.hpp>#include <boost/property_tree/ini_parser.hpp> .. ...
- 修改Android 4.2.2的原生Camera引出的java.lang.UnsatisfiedLinkError: Native method not found,及解决方法
修改Android 4.2.2的原生Camera应用,做一些定制,将Camera的包名从之前的 package com.android.* 修改成了com.zhao3546.*. 调整后,应用可以正常 ...
- unity3d游戏开发猜想——当程序猿老去
程序猿将代码注入生命去打造互联网的浪潮之巅.当有一天他们老了.会走向那里,会做些什么? 4.4.0" alt="" style="border:0px; ver ...