Java Class.getResource和ClassLoader.getResource的使用

来源:互联网 发布:开源数据库排名 编辑:程序博客网 时间:2024/06/10 17:26

Java中获取资源文件的时候,经常会用到Class.getResource和ClassLoader.getResource,本文给大家说一下这两者方法在获取资源文件时的路径差异。
Class.getResource(String path)
path不以’/’开头时,默认是从此类所在的包下取资源;
path以’/’开头时,则是从项目的ClassPath根下获取资源。在这里’/’表示ClassPath
JDK设置这样的规则,是很好理解的,path不以’/’开头时,我们就能获取与当前类所在的路径相同的资源文件,而以’/’开头时可以获取ClassPath根下任意路径的资源。
如下所示的例子:

package test.path;public class Test{    public static void main(String[] args)    {        System.out.println(Test.class.getResource(""));        System.out.println(Test.class.getResource("/"));    }}

运行结果为:
file:/E:/JAVA/Workspaces/test/bin/test/path/
file:/E:/JAVA/Workspaces/test/bin/
Class.getClassLoader().getResource(String path)
path不能以’/’开头时,path是指类加载器的加载范围,在资源加载的过程中,使用的逐级向上委托的形式加载的,’/’表示Boot ClassLoader中的加载范围,因为这个类加载器是C++实现的,所以加载范围为null。如下所示:

package test.path;public class Test{    public static void main(String[] args)    {        System.out.println(Test.class.getClassLoader().getResource(""));        System.out.println(Test.class.getClassLoader().getResource("/"));    }}

运行结果为:
file:/E:/JAVA/Workspaces/test/bin/
null
从上面可以看出:
class.getResource(“/”) == class.getClassLoader().getResource(“”)
其实,Class.getResource和ClassLoader.getResource本质上是一样的,都是使用ClassLoader.getResource加载资源的。下面请看一下jdk的Class源码:

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);    }

从上面就可以看才出来:Class.getResource和ClassLoader.getResource本质上是一样的。至于为什么Class.getResource(String path)中path可以’/’开头,是因为在name = resolveName(name);进行了处理:

    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;    }

System.getProperty(“java.class.path”)同样也是获取calsspath路径

package test.path;import java.io.File;import java.io.IOException;import java.net.URL;public class Test {    public static void main(String[] args) throws IOException {        // 得到java.class.path路径        File f = new File(Test.class.getResource("/").getPath());        System.out.println(f);        System.out.println(Test.class.getResource("/").getPath());        System.out.println(System.getProperty("java.class.path"));        System.out.println("-------");        URL xmlpath = Test.class.getClassLoader().getResource("");        System.out.println(xmlpath);        System.out.println(xmlpath.getFile());        System.out.println(xmlpath.getPath());        System.out.println(Test.class.getClassLoader().getResource("/"));        System.out.println("----------------------------------------------");        // 得到当前类路径        File f2 = new File(Test.class.getResource("").getPath());        System.out.println(f2);        File directory = new File("");        String courseFile = directory.getCanonicalPath();        System.out.println(courseFile);        System.out.println(System.getProperty("user.dir"));    }}

运行结果

E:\JAVA\Workspaces\test\bin/E:/JAVA/Workspaces/test/bin/E:\JAVA\Workspaces\test\bin-------file:/E:/JAVA/Workspaces/test/bin//E:/JAVA/Workspaces/test/bin//E:/JAVA/Workspaces/test/bin/null----------------------------------------------E:\JAVA\Workspaces\test\bin\test\pathE:\JAVA\Workspaces\testE:\JAVA\Workspaces\test

还有一个getResourceAsStream()方法,参数是与getResouce()方法是一样的,它相当于你用getResource()取得File文件后,再new InputStream(file)一样的结果
推荐获取文件方法:
File file=new File(xxx.class.getClassLoader().getResource(“test.txt”).getFile());
如果是web项目classpath路径为WEB-INF/classes

0 0
原创粉丝点击