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)
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining 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 ClassLoader.getSystemResourceAsStream(java.lang.String).

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

    • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
    • Otherwise, the absolute name is of the following form:

      modified_package_name/name

      Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

Parameters:
name - name of the desired resource
Returns:
InputStream object or null if no resource with this name is found
Throws:
NullPointerException - If name is null

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()的更多相关文章

  1. Class.getResourceAsStream和ClassLoader.getResourceAsStream方法

    项目中,有时候要读取当前classpath下的一些配置文件,下面介绍下Class.getResourceAsStream和ClassLoader.getResourceAsStream两种方法以及两者 ...

  2. Class.getResourceAsStream()与ClassLoader.getResourceAsStream()的区别

    Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.clas ...

  3. 对Class.getResourceAsStream和ClassLoader.getResourceAsStream方法所使用的资源路径的解释

    这是个非常基础的问题了,这里提供一些演示样例,帮助高速理解和记忆这个问题. 在该方法的文档:http://docs.oracle.com/javase/7/docs/api/java/lang/Cla ...

  4. Class.getResourceAsStream()与ClassLoader.getResourceAsStream()获取资源时的路径说明

    Class.getResourceAsStream(): com.xusweeter.iot.ws.vodafone.config.VodafoneServiceConfig.class.getRes ...

  5. class getResourceAsStream 和 classloader getResourceAsStream获取资源的不同

    工程目录结构: prj(工程根目录) cn json classloader GetResourceByClassAndClassLoader.Java beans.xml /** * */ pack ...

  6. JAVA 笔记 ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别

       Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.c ...

  7. ClassLoader.getResourceAsStream() 与 Class.getResourceAsStream()的区别

        Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致. 例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest. ...

  8. classLoader.getResourceAsStream中文乱码

    一直用一个方法安然无恙,今天在新项目中突然乱码了,原代码: ClassLoader classLoader = Thread.currentThread().getContextClassLoader ...

  9. 1、ClassLoader.getResourceAsStream() 与Class.getResourceAsStream()的区别

    1.ClassLoader.getResourceAsStream() 与Class.getResourceAsStream()的区别 例如你写了一个MyTest类在包com.test.mycode ...

随机推荐

  1. iOS开发中代理使用出现的问题解决

    在给自定义的LHQTabBar设置代理的时候,定义的代理的属性的时候此时会报一个警告 我们需要遵守UITabBarDelegate的协议才行, 不过此时还有警告,警告已经变成了 此时我们需要在.m文件 ...

  2. GridVeiw 使用

    1. 因使用的是 Mongodb,因此要在 ActiveDataProvider 中指定 key 属性 2. 自定义表格中的按钮 'class' => 'yii\grid\ActionColum ...

  3. navicat从下载到使用

    ☆准备工作 确保电脑安装了mysql数据库 确定my.ini下的字符集设置为utf8 ☆下载navicat 输入网址 https://www.navicat.com 点击Downloads 点击Dow ...

  4. 在windows下使用gnu的工具

    mingw Minimalist GNU for Windows http://www.mingw.org/ 想要在Windows使用wget,之前使用的是单独的安装包,现在又想使用bash的命令提示 ...

  5. Nvidia Anisotropic Lighting

    http://http.download.nvidia.com/developer/SDK/Individual_Samples/DEMOS/Direct3D9/HLSL_Aniso.zip Anis ...

  6. 每天php函数 - str_replace()

    mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) 该函数返回一个字符 ...

  7. SnapKit代码约束

    let label = UILabel() label.frame = CGRectMake(, , , ) label.backgroundColor = UIColor.cyanColor() l ...

  8. Unity 区分不同平台

    问题:公司开发的游戏实在android平台上运行,但是我们是在windows平台下进行开发,OK ,经常有些地方开发完之后就要换到android上面,能区分平台的不同就可以对代码做区分处理 回答:un ...

  9. QQ群笔记

     uuid就好比你的名字,类似到了班级里,你的名字会被学号替代.同样的连接之后,uuid会被handle句柄替代.   问下CC2541串口用DMA接收的时候,调试程序时候发现,串口发一帧数据,进入两 ...

  10. 动态加载js,css

    今天项目中需要用到动态加载 CSS 文件,经过一番折腾终于搞定,回家整理了一下,顺便融合了动态加载 JS 的功能写成了一个对象,先上代码: var dynamicLoading = { css: fu ...