Resource Components of Spring

1.资源组件UML类图

资源组件接口中核心方法:exists(), isopen(), isReadable(), getInputStream()
引用核心的Java API:File类,URL类
2.重点介绍UrlResource和ClasspathResource
UrlResource
     利用统一资源标识符或者定位符加载资源,其中UrlResource封装了Url,UrlConnection的操作。持有Url,Uri等对象。UrlResource的exists(), isReadable()方法继承自父类AbstractResourceResolving。提供了利用Url变量得到文件File。用File类的方法操作资源,验证资源的可读性,是否存在,是否可被打开!通过UrlConnection获取资源的输入流!
例如:
public InputStream getInputStream() throws IOException {
URLConnection con = this. url.openConnection();
ResourceUtils.useCachesIfNecessary( con);
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if ( con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}

ClassPathResource
此对象用来获取class path下的资源,其中ClassPathResource持有Class, ClassLoader等对象。利用Class和ClassLoader对象的getResource()和getResourceStream()方法操作资源,妥妥的!
例如:
判断资源是否存在
public boolean exists() {
return (resolveURL() != null);
 }

protected URL resolveURL() {
if ( this. clazz != null) {
return this. clazz.getResource( this. path);
}
else if ( this. classLoader != null) {
return this. classLoader.getResource( this. path);
}
else {
return ClassLoader.getSystemResource( this. path);
}
}



获取资源的输入流对象
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(getDescription() + " cannot be opened because it does not exist");
}
return is;

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值