4.2  内置Resource实现

4.2.1  ByteArrayResource

ByteArrayResource代表byte[]数组资源,对于“getInputStream”操作将返回一个ByteArrayInputStream。

首先让我们看下使用ByteArrayResource如何处理byte数组资源:

      package cn.javass.spring.chapter4;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
public class ResourceTest {
@Test
public void testByteArrayResource() {
Resource resource = new ByteArrayResource("Hello World!".getBytes());
if(resource.exists()) {
dumpStream(resource);
}
}
}

  是不是很简单,让我们看下“dumpStream”实现:

private void dumpStream(Resource resource) {
InputStream is = null;
try {
//1.获取文件资源
is = resource.getInputStream();
//2.读取资源
byte[] descBytes = new byte[is.available()];
is.read(descBytes);
System.out.println(new String(descBytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
//3.关闭资源
is.close();
} catch (IOException e) {
}
}
}

  

让我们来仔细看一下代码,dumpStream方法很抽象定义了访问流的三部曲:打开资源、读取资源、关闭资源,所以dunpStrean可以再进行抽象从而能在自己项目中使用;byteArrayResourceTest测试方法,也定义了基本步骤:定义资源、验证资源存在、访问资源。

ByteArrayResource可多次读取数组资源,即isOpen ()永远返回false。

1.2.2  InputStreamResource

InputStreamResource代表java.io.InputStream字节流,对于“getInputStream ”操作将直接返回该字节流,因此只能读取一次该字节流,即“isOpen”永远返回true。

让我们看下测试代码吧:

@Test
public void testInputStreamResource() {
ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
Resource resource = new InputStreamResource(bis);
if(resource.exists()) {
dumpStream(resource);
}
Assert.assertEquals(true, resource.isOpen());
}

  

测试代码几乎和ByteArrayResource测试完全一样,注意“isOpen”此处用于返回true。

4.2.3  FileSystemResource

FileSystemResource代表java.io.File资源,对于“getInputStream ”操作将返回底层文件的字节流,“isOpen”将永远返回false,从而表示可多次读取底层文件的字节流。

让我们看下测试代码吧:

@Test
public void testFileResource() {
File file = new File("d:/test.txt");
Resource resource = new FileSystemResource(file);
if(resource.exists()) {
dumpStream(resource);
}
Assert.assertEquals(false, resource.isOpen());
}

  

注意由于“isOpen”将永远返回false,所以可以多次调用dumpStream(resource)。

4.2.4  ClassPathResource

ClassPathResource代表classpath路径的资源,将使用ClassLoader进行加载资源。classpath 资源存在于类路径中的文件系统中或jar包里,且“isOpen”永远返回false,表示可多次读取资源。

ClassPathResource加载资源替代了Class类和ClassLoader类的“getResource(String name)”和“getResourceAsStream(String name)”两个加载类路径资源方法,提供一致的访问方式。

ClassPathResource提供了三个构造器:

public ClassPathResource(String path):使用默认的ClassLoader加载“path”类路径资源;

public ClassPathResource(String path, ClassLoader classLoader)使用指定的ClassLoader加载“path”类路径资源;

比如当前类路径是“cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring/chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4/test1.properties”;

public ClassPathResource(String path, Class<?> clazz)使用指定的类加载“path”类路径资源,将加载相对于当前类的路径的资源;

比如当前类路径是“cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring/chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4/cn/javass/spring/chapter4/test1.properties”;

而如果需要 加载的资源路径为“test1.properties”,将加载的资源为“cn/javass/spring/chapter4/test1.properties”。

让我们直接看测试代码吧:

1)使用默认的加载器加载资源,将加载当前ClassLoader类路径上相对于根路径的资源:

@Test
public void testClasspathResourceByDefaultClassLoader() throws IOException {
Resource resource = new ClassPathResource("cn/javass/spring/chapter4/test1.properties");
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}

  2)使用指定的ClassLoader进行加载资源,将加载指定的ClassLoader类路径上相对于根路径的资源:

@Test
public void testClasspathResourceByClassLoader() throws IOException {
ClassLoader cl = this.getClass().getClassLoader();
Resource resource = new ClassPathResource("chapter4/test1.properties" , cl);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}

  3)使用指定的类进行加载资源,将尝试加载相对于当前类的路径的资源:

@Test
public void testClasspathResourceByClass() throws IOException {
Class clazz = this.getClass();
Resource resource1 = new ClassPathResource("test1.properties" , clazz);
if(resource1.exists()) {
dumpStream(resource1);
}
System.out.println("path:" + resource1.getFile().getAbsolutePath());
Assert.assertEquals(false, resource1.isOpen()); Resource resource2 = new ClassPathResource("test1.properties" , this.getClass());
if(resource2.exists()) {
dumpStream(resource2);
}
System.out.println("path:" + resource2.getFile().getAbsolutePath());
Assert.assertEquals(false, resource2.isOpen());
}

  

“resource1”将加载cn/javass/spring/chapter4/cn/javass/spring/chapter4/test1.properties资源;“resource2”将加载“cn/javass/spring/chapter4/test1.properties”;

4)加载jar包里的资源,首先在当前类路径下找不到,最后才到Jar包里找,而且在第一个Jar包里找到的将被返回:

@Test
public void classpathResourceTestFromJar() throws IOException {
Resource resource = new ClassPathResource("overview.html");
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getURL().getPath());
Assert.assertEquals(false, resource.isOpen());
}

  

如果当前类路径包含“overview.html”,在项目的“resources”目录下,将加载该资源,否则将加载Jar包里的“overview.html”,而且不能使用“resource.getFile()”,应该使用“resource.getURL()”,因为资源不存在于文件系统而是存在于jar包里,URL类似于“file:/C:/.../***.jar!/overview.html”。

类路径一般都是相对路径,即相对于类路径或相对于当前类的路径,因此如果使用“/test1.properties”带前缀“/”的路径,将自动删除“/”得到“test1.properties”。

4.2.5  UrlResource

UrlResource代表URL资源,用于简化URL资源访问。“isOpen”永远返回false,表示可多次读取资源。

UrlResource一般支持如下资源访问:

http通过标准的http协议访问web资源,如new UrlResource(“http://地址”);

ftp通过ftp协议访问资源,如new UrlResource(“ftp://地址”);

file通过file协议访问本地文件系统资源,如new UrlResource(“file:d:/test.txt”);

具体使用方法在此就不演示了,可以参考cn.javass.spring.chapter4.ResourceTest中urlResourceTest测试方法。

public void testUrlResource()
{
try {
Resource resource = new UrlResource( "file:d:/goods.txt" );
if(resource.exists())
{
InputStream is = null;
try {
//读取文件资源
is = resource.getInputStream();
//读取资源
//资源总量
byte[] bytes = new byte[is.available()];
//读
is.read(bytes);
//输出
System.out.println(new String(bytes)); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
System.out.println("path:"+resource.getURL().getPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assert.assertEquals(false, resource.isOpen()); } } catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} @Test
public void testHttp()
{
try {
//读取文件资源
Resource resource = new UrlResource("http://jinnianshilongnian.iteye.com/");
//读取资源
InputStream is = null;
try {
//读取Inputstream资源
is = resource.getInputStream();
//获取资源的总量
byte[] bytes = new byte[is.available()];
is.read(bytes);
System.out.println(new String(bytes)); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} try {
System.out.println("path:"+resource.getURL().getPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Assert.assertEquals(false, resource.isOpen());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

  

4.2.6  ServletContextResource

ServletContextResource代表web应用资源,用于简化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作;在此就不具体演示了。

4.2.7  VfsResource

VfsResource代表Jboss 虚拟文件系统资源。

Jboss VFS(Virtual File System)框架是一个文件系统资源访问的抽象层,它能一致的访问物理文件系统、jar资源、zip资源、war资源等,VFS能把这些资源一致的映射到一个目录上,访问它们就像访问物理文件资源一样,而其实这些资源不存在于物理文件系统。

在示例之前需要准备一些jar包,在此我们使用的是Jboss VFS3版本,可以下载最新的Jboss AS 6x,拷贝lib目录下的“jboss-logging.jar”和“jboss-vfs.jar”两个jar包拷贝到我们项目的lib目录中并添加到“Java Build Path”中的“Libaries”中。

让我们看下示例(cn.javass.spring.chapter4.ResourceTest):

 @Test
public void testVfsResource1() throws IOException {
VirtualFile virtualFile = VFS.getChild("d:/test.txt");
Resource resource = new VfsResource(virtualFile);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getURL().getPath());
Assert.assertEquals(false, resource.isOpen()); } @Test
public void testVfsResourceForRealFileSystem() throws IOException {
//1.创建一个虚拟的文件目录
VirtualFile home = VFS.getChild("/home");
//2.将虚拟目录映射到物理的目录
VFS.mount(home, new RealFileSystem(new File("d:")));
//3.通过虚拟目录获取文件资源
VirtualFile testFile = home.getChild("test.txt");
//4.通过一致的接口访问
Resource resource = new VfsResource(testFile);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen()); } @Test
public void testVfsResourceForJar() throws IOException {
//1.首先获取jar包路径
File realFile = new File("lib/org.springframework.beans-3.0.5.RELEASE.jar");
//2.创建一个虚拟的文件目录
VirtualFile home = VFS.getChild("/home2");
//3.将虚拟目录映射到物理的目录
VFS.mountZipExpanded(realFile, home, TempFileProvider.create("tmp", Executors.newScheduledThreadPool(1)));
//4.通过虚拟目录获取文件资源
VirtualFile testFile = home.getChild("META-INF/spring.handlers");
//5.通过一致的接口访问
Resource resource = new VfsResource(testFile);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen()); } private void dumpStream(Resource resource) {
InputStream is = null;
try {
//1.获取文件资源
is = resource.getInputStream();
//2.读取资源
byte[] descBytes = new byte[is.available()];
is.read(descBytes);
System.out.println(new String(descBytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
//3.关闭资源
is.close();
} catch (IOException e) {
}
}
}

  

spring3: 内置Resource实现的更多相关文章

  1. 开涛spring3(4.2) - 资源 之 4.2 内置Resource实现

    4.2  内置Resource实现 4.2.1  ByteArrayResource ByteArrayResource代表byte[]数组资源,对于“getInputStream”操作将返回一个By ...

  2. 资源 之 4.2 内置Resource实现(拾)

    4.2  内置Resource实现 4.2.1  ByteArrayResource ByteArrayResource代表byte[]数组资源,对于"getInputStream" ...

  3. Spring系列18:Resource接口及内置实现

    本文内容 Resource接口的定义 Resource接口的内置实现 ResourceLoader接口 ResourceLoaderAware 接口 Resource接口的定义 Java 的标准 ja ...

  4. Java第三方数据库连接池库-DBCP-C3P0-Tomcat内置连接池

    连接池原理 数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”.预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去.我们可以通过设定连接池 ...

  5. Webstorm 2016内置web服务器配置

    运行three.js的官方的例子.本来想用IIS来运行,运行不了.所以用webstorm,用鼠标右键的方式,来运行,如下图 但是有一天,我把IIS配置好了,可以在IIS中运行了(只是把build文件夹 ...

  6. Eclipse spket插件 内置js文件

    这一篇将怎么在spket内置js文件,而不用用户自己去添加.    1. 在开发的Eclipse的 运行配置将下面几个插件勾选上.     2. 在org.eclipse.ui.startup拓展里执 ...

  7. 前端MVC学习总结(三)——AngularJS服务、路由、内置API、jQueryLite

    一.服务 AngularJS功能最基本的组件之一是服务(Service).服务为你的应用提供基于任务的功能.服务可以被视为重复使用的执行一个或多个相关任务的代码块. AngularJS服务是单例对象, ...

  8. [转]重新分配内置存储空间 android手机

    本文转自:http://www.in189.com/thread-815721-1-1.html 鉴于有些同学遇到问题了,毕竟步骤繁琐,可能中间会出错,因此推荐用26L       338944    ...

  9. 《JavaScript 闯关记》之单体内置对象

    ECMA-262 对内置对象的定义是「由 JavaScript 实现提供的.不依赖于宿主环境的对象,这些对象在 JavaScript 程序执行之前就已经存在了」.意思就是说,开发人员不必显式地实例化内 ...

随机推荐

  1. xshell 没有反应---Xshell按ctrl+s界面无反应的解决办法

    在用Xshell管理远程服务器,特别是在用vi编辑配置文件时,总是习惯的用ctrl+s想要保存文件,然后就悲剧了.xsell就再也没有返应只能关了重新打开.但原来修改的文件算是报废了. 在网上搜索了一 ...

  2. 1.java中Comparor与Comparable的问题

    1.Comparator中compare()与Comparable中compareTo()方法的区别 Treeset集合创建对象后, A:如果是空构造,即TreeSet<Student> ...

  3. 中间件MQ选型要点

    转载自:  https://www.cnblogs.com/doit8791/p/10227474.html 参考: http://www.52im.net/thread-1647-1-1.html ...

  4. 处理界面上使用两个jq的报错

    转载:http://www.365mini.com/page/jquery_noconflict.htm <script src="jquery-1.9.1.js">& ...

  5. jquery获取浏览器类型和版本号的方法

    $(document).ready(function(){ varbrow=$.browser; varbInfo=""; if(brow.msie){bInfo="Mi ...

  6. django博客项目3:创建 Django 博客的数据库模型

    设计博客的数据库表结构 博客最主要的功能就是展示我们写的文章,它需要从某个地方获取博客文章数据才能把文章展示出来,通常来说这个地方就是数据库.我们把写好的文章永久地保存在数据库里,当用户访问我们的博客 ...

  7. linux c编程:Posix信号量

    POSIX信号量接口,意在解决XSI信号量接口的几个不足之处: POSIX信号量接口相比于XSI信号量接口,允许更高性能的实现. POSIX信号量接口简单易用:没有信号量集,其中一些接口模仿了我们熟悉 ...

  8. corethink功能模块探索开发(十八)前台页面插入jit前端数据可视化库

    效果图: 1.静态文件放入View目录中 在View目录下新建Public目录,在Public目录下新建js.css目录. 把jit的资源放入对应目录中 2.在html中引入jit Applicati ...

  9. Tensorflow 学习笔记(一)TensorFlow入门

    一.计算模型----计算图 1.1 计算图的概念:TensorFlow就是通过图的形式绘制出张量节点的计算过程,例如下图执行了一个a+b的操作. 1.2 计算图的使用 TensorFlow程序一般分为 ...

  10. C# 建立UDP服务器并接收客户端数据

    C# 建立UDP服务器并接收客户端数据 2015-02-11 17:20 1218人阅读 评论(0) 收藏 举报  分类: C#开发技术(22)  版权声明:本文为博主原创文章,未经博主允许不得转载. ...