Spring的Resource接口,相比于URL而言,更强大,抽象了对低级资源的访问。
定义如下:
public interface Resource extends InputStreamSource {
boolean exists();
boolean isOpen();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
其中,有四个方法需要留意:
getInputStream()
打开资源,获取一个InputStream,并返回,每次调用都会产生一个新的InputStream,调用 者负责关闭流
exists()
返回boolean以标记资源是否以物理形式存在
isOpen()
返回资源是否被打开
getDescription()
返回资源的描述,用语处理资源错误的时候的输出
使用ApplicationContext获取Resource时,根据参数的前缀,会分配不同的ResourceLoader,如:
ctx.getResource("classpath:xxxx") => 返回ClassPathResource
ctx.getResource("file:xxxx") => 返回FileSystemResource
ctx.getResource("http:xxxx") => 返回ServletContextResource
原文:https://www.cnblogs.com/kuromaru/p/12931287.html