Class.getResourceAsStream() VS. ClassLoader.getResourceAsStream()
For Class.getResourceAsStream(String name),
- if the name parameter doesn't start with a "/", then it's a relative path to the class's package.
- If the name parameter starts with a "/", then it's an absolute path.
For ClassLoader.getResourceAsStream(String name),
- the name parameter is always an absolute path.
- and it can never start with a "/",if it does, the resource is never found.
If the file cannot be found, both methods return null and no exception is thrown.
The following program illustrates the difference.
Project structure

ResourceAsStream.java
public class ResourceAsStream {
/**
* @param args
*/
public static void main(String[] args) {
String path1 = "a.properties";
String path2 = "/a.properties";
String path3 = "test/a.properties";
String path4 = "/test/a.properties";
System.out.println("Class.getResourceAsStream()");
InputStream is = ResourceAsStream.class.getResourceAsStream(path1);
System.out.println(path1 + " " + (is != null));
is = ResourceAsStream.class.getResourceAsStream(path2);
System.out.println(path2 + " " + (is != null));
is = ResourceAsStream.class.getResourceAsStream(path3);
System.out.println(path3 + " " + (is != null));
is = ResourceAsStream.class.getResourceAsStream(path4);
System.out.println(path4 + " " + (is != null));
System.out.println();
System.out.println("ClassLoader.getResourceAsStream()");
is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path1);
System.out.println(path1 + " " + (is != null));
is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path2);
System.out.println(path2 + " " + (is != null));
is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path3);
System.out.println(path3 + " " + (is != null));
is = ResourceAsStream.class.getClassLoader().getResourceAsStream(path4);
System.out.println(path4 + " " + (is != null));
}
}
Result:
Class.getResourceAsStream()
a.properties true
/a.properties false
test/a.properties false
/test/a.properties true ClassLoader.getResourceAsStream()
a.properties false
/a.properties false
test/a.properties true
/test/a.properties false JDK explanation about this two method Class.java public InputStream getResourceAsStream(String name)
ClassLoader.getSystemResourceAsStream(java.lang.String).
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the
namebegins with a'/'('\u002f'), then the absolute name of the resource is the portion of thenamefollowing the'/'. - Otherwise, the absolute name is of the following form:
modified_package_name/nameWhere the
modified_package_nameis the package name of this object with'/'substituted for'.'('\u002e').
- If the
- Parameters:
name- name of the desired resource- Returns:
- A
InputStreamobject ornullif no resource with this name is found - Throws:
NullPointerException- Ifnameisnull
ClassLoader.java
public InputStream getResourceAsStream(String name)
Returns an input stream for reading the specified resource.
The search order is described in the documentation for getResource(String).
Parameters:
name - The resource name
Returns:
An input stream for reading the resource, or null if the resource could not be found
Since:
1.1
public URL getResource(String name)
Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
The name of a resource is a '/'-separated path name that identifies the resource. --here it means absolute path
This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invokefindResource(String) to find the resource.
Parameters:
name - The resource name
Returns:
A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Since:
1.1
below from http://www.javaworld.com/article/2077404/core-java/got-resources-.html
Because Class.getResource() eventually delegates toClassLoader.getResource(), the two methods are indeed very similar.
However, the first method is often preferable. It provides a nice extra feature: it looks up package-local resources.
As an example, this code snippet getClass().getResource("settings.properties"); executed from a class some.pkg.MyClass
looks for a resource deployed a ssome/pkg/settings.properties.You might wonder why this is better then the equivalent
getClass().getClassLoader().getResource("some/pkg/settings.properties");
The reason is the possibility for future refactoring. Should you decide to rename pkgto betterpkgname and move all classes and resources into the new
package, the first code snippet requires no further code changes. The second code snippet embeds the old package name in a string literal—something that
is easy to forget and can become a runtime error later. Another advantage of Class.getResource() is that it does not require thegetClassLoader runtime
security permission, which the other approach requires.
I should mention a few extra details. Is it better to acquire the relevant Class object using the getClass() instance method or using MyClass.class?
The answer depends on whether you plan to have classes in other packages extend MyClass.
Since get Class() always returns the most derived class, it might return a class in a package different from some.pkg, possibly coded after MyClass is
conceived. If this is a possibility, you should safeguard against potential lookup errors by using the class literal syntax form, MyClass.class. As an added
benefit, it also works from static methods.
Class.getResourceAsStream() VS. ClassLoader.getResourceAsStream()的更多相关文章
- Class.getResourceAsStream和ClassLoader.getResourceAsStream方法
项目中,有时候要读取当前classpath下的一些配置文件,下面介绍下Class.getResourceAsStream和ClassLoader.getResourceAsStream两种方法以及两者 ...
- Class.getResourceAsStream()与ClassLoader.getResourceAsStream()的区别
Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.clas ...
- 对Class.getResourceAsStream和ClassLoader.getResourceAsStream方法所使用的资源路径的解释
这是个非常基础的问题了,这里提供一些演示样例,帮助高速理解和记忆这个问题. 在该方法的文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Cla ...
- Class.getResourceAsStream()与ClassLoader.getResourceAsStream()获取资源时的路径说明
Class.getResourceAsStream(): com.xusweeter.iot.ws.vodafone.config.VodafoneServiceConfig.class.getRes ...
- class getResourceAsStream 和 classloader getResourceAsStream获取资源的不同
工程目录结构: prj(工程根目录) cn json classloader GetResourceByClassAndClassLoader.Java beans.xml /** * */ pack ...
- JAVA 笔记 ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别
Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.c ...
- ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别
Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest. ...
- classLoader.getResourceAsStream中文乱码
一直用一个方法安然无恙,今天在新项目中突然乱码了,原代码: ClassLoader classLoader = Thread.currentThread().getContextClassLoader ...
- 1、ClassLoader.getResourceAsStream() 与Class.getResourceAsStream()的区别
1.ClassLoader.getResourceAsStream() 与Class.getResourceAsStream()的区别 例如你写了一个MyTest类在包com.test.mycode ...
随机推荐
- ThinkPHP 中M方法和D方法详解----转载
转载的地址,http://blog.163.com/litianyichuanqi@126/blog/static/115979441201223043452383/ 自己学到这里的时候,不能清除的分 ...
- JAVA字符串转日期或日期转字
文章中,用的API是SimpleDateFormat,它是属于java.text.SimpleDateFormat,所以请记得import进来! 用法: SimpleDateFormat sdf ...
- HTML练习----注册界面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 换行符javajava去除字符串中的空格、回车、换行符、制表符
在改章节中,我们主要介绍换行符java的内容,自我感觉有个不错的建议和大家分享下 每日一道理 只有启程,才会到达理想和目的地,只有拼搏,才会获得辉煌的成功,只有播种,才会有收获.只有追求,才会 ...
- PHP 错误与异常 笔记与总结(14 )记录和发送异常信息
当发生异常时,把异常信息记录到日志文件中: <?php header('content-type:text/html; charset=utf-8'); class LogException e ...
- Javascript 笔记与总结(2-9)获取运行时的 style 对象
获取内存中(正在渲染)的 style 的值(非内联 style,obj.style 只能获得内联 style 的值),可以用 obj.currentStyle(低版本 IE 和 Opera 支持)和 ...
- Ubuntu 卸载 VMware
sudo vmware-installer --uninstall-product vmware-workstationsudo vmware-installer --uninstall-produc ...
- php 去除html标记--strip_tags与htmlspecialchars的区别详解
php 去除html标记--strip_tags与htmlspecialchars的区别详解 作者: 字体:[增加 减小] 类型:转载 时间:2013-06-26 本篇文章是对php中去除html ...
- 基于LR的Oracle应用性能测试
最近对一个oracle ERP系统的INV模块进行性能测试,因为之前大部分都是测试web类型的应用,在这方面经验较少,期间也遇到了不少问题,因此有必要作些总结,以备后忘.首先先简单了解下测试对象相关的 ...
- Andrew Ng机器学习公开课笔记 -- Online Learning
网易公开课,第11课 notes,http://cs229.stanford.edu/notes/cs229-notes6.pdf 和之前看到的batch learning算法不一样,batch ...