概述
开发中需要处理很多的外部资源(URL资源、File资源、ClassPath相关资源、服务器相关资源等),使用这些资源需要用到不同的接口,这就增加系统的复杂程度。
处理这些资源的步骤基本类似(1打开资源,2读取资源,3关闭资源)。
所以Spring提供了一个Resource的接口来统一进行这些底层的资源的访问。
Resource接口
Resource.class
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
public abstract interface Resource extends InputStreamSource
{
public abstract boolean exists();
public abstract boolean isReadable();
public abstract boolean isOpen();
public abstract URL getURL()
throws IOException;
public abstract URI getURI()
throws IOException;
public abstract File getFile()
throws IOException;
public abstract long contentLength()
throws IOException;
public abstract long lastModified()
throws IOException;
public abstract Resource createRelative(String paramString)
throws IOException;
public abstract String getFilename();
public abstract String getDescription();
}
InputStreamSource.class
package org.springframework.core.io;
import java.io.IOException;
import java.io.InputStream;
public abstract interface InputStreamSource
{
public abstract InputStream getInputStream()
throws IOException;
}
- InputStreamSource接口
getInputStream每次调用都返回一个资源对应的java.io.InputStream
的字节流,调用完之后必须关闭该资源 Resource接口集成InputStreamSource接口,并提供了一些方法:
- exists:判断Resource代表的资源是否存在,存在返回true;
isReadable:返回当前Resource代表的资源是否可读,可读则返回true;
getURL:如果当前的Resource代表的资源由java.util.URL代表,返回该URL,否则抛出IO异常
getURI:如果当前的Resource代表的资源由java.util.URL代表,返回该URI,否则抛出IO异常
getFile:如果当前的Resource代表的资源由java.io.File代表,返回该File,否则抛出IO异常
- contentLength:返回当前Resource代表的文件资源的长度
- lastModified:返回当前Resource代表的底层资源的最后修改时间
- createRelative:用于创建相对于当前Resource代表的资源,比如当前Resource代表文件资源”d:/a/”,则Resource.createRelative(“test.txt”),将返回”d:/a/test.txt”的资源
- getFilename:返回的是当前Resource代表的文件资源的路径,例如有File资源”d:/test.txt”将返回”test.txt”,而URL资源将返回“”
- getDescription:返回当前Resource代表的资源的描述符,通常就是资源的全路径(实际的文件名或者实际的URL地址),例如有File资源”d:/test.txt”将返回”file [d:\test.txt]”,而URL资源
"http://www.baidu.com"
将返回"URL [http://www.baidu.com]"
package com.test;
import java.net.MalformedURLException;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import junit.framework.TestCase;
public class ResourceTest extends TestCase {
public void testResource(){
Resource resource=new FileSystemResource("d:/test.txt");
try {
Resource resource2=new UrlResource("http://www.baidu.com");
System.out.println(resource2.getFilename());
System.out.println(resource2.getDescription());
} catch (MalformedURLException e) {
e.printStackTrace();
}
System.out.println(resource.getFilename());
System.out.println(resource.getDescription());
}
}
Resource接口提供了足够的抽象。而且提供了很多Resource的实现:
- ByteArrayResouce
- InputStreamResource
- FileSystemResource
- UrlResource
- ClassPathResource
- ServletContextResource
- VfsResource