ClassPath资源的读取

读取ClassPath的资源

在程序中经常有很多资源需要读取,常见的就是配置文件,Java中将文件当作一种资源来处理,可以使用Class或者ClassLoader来处理

一,使用Class类的getSourceAsStream方法

该方法接受一个文件路径字符串参数,表示文件的路径,这个路径有两种写法:

  1. 以"/"开头,表示以类路径为起始目录
  2. 不以"/"开头,表示相对于当前类的相对路径

其实Class类的getResourceAsStream最终也是委托加载该Class的ClassLoader去加载文件的

二,使用ClassLoader来加载

ClassLoader中有一个方法是getSourceAsStream,该方法的使用方式和上面的不一样,该方法不能以"/"开头,方法的参数表示以类路径为起始路径

Spring中ClassPath资源的读取

在spring中对资源的读取也做了抽象,spring将所有的资源抽象为Resource类,对于classpath下的资源有与之对应的类ClassPathResource,其实在这个类中同样也是使用了上面的方法来加载类路径下的资源,这里贴一部分spring中ClassPahtResource读取资源的代码:

// 获取资源URL
protected URL resolveURL() {
    if (this.clazz != null) {
        return this.clazz.getResource(this.path);
    } else {
        return this.classLoader != null ? this.classLoader.getResource(this.path) : ClassLoader.getSystemResource(this.path);
    }
}

// 获取资源IO流
public InputStream getInputStream() throws IOException {
    InputStream is;
    if (this.clazz != null) {
        is = this.clazz.getResourceAsStream(this.path);
    } else if (this.classLoader != null) {
        is = this.classLoader.getResourceAsStream(this.path);
    } else {
        is = ClassLoader.getSystemResourceAsStream(this.path);
    }

    if (is == null) {
        throw new FileNotFoundException(this.getDescription() + " cannot be opened because it does not exist");
    } else {
        return is;
    }
}

猜你喜欢

转载自www.cnblogs.com/watertreestar/p/11939174.html