(七)Spring详解——资源Resource接口

来源:互联网 发布:centos更改ip地址 编辑:程序博客网 时间:2024/05/20 05:53

Spring提供了一个Resource接口来统一对底层资源的方便访问,并提供了一些接口方法来完成常见操作。
Resouce接口
继承自InputStreamSource

  • getInputStream:每次调用都将返回一个新鲜的资源对应的java.io. InputStream字节流,调用者在使用完毕后必须关闭该资源。

Resource提供接口方法

  • exists:返回当前Resource代表的底层资源是否存在
  • isReadable:返回当前Resource代表的底层资源是否存在
  • isOpen返回当前Resource代表的底层资源是否打开
  • getURL,getURI,getFile等,功能如其名
  • contentLength返回当前底层资源长度
  • lastModified返回当前Resource代表的底层文件资源最后修改时间
  • getFilename:返回当前Resource代表的底层文件资源的文件路径,比如File资源“file://d:/test.txt”将返回“d:/test.txt”,而URL资源http://www.javass.cn将返回“”,因为只返回文件路径。
  • getDescription:返回当前Resource代表的底层资源的描述符,通常就是资源的全路径(实际文件名或实际URL地址)。

Resource实现:
ByteArrayResource、InputStreamResource 、FileSystemResource 、UrlResource 、ClassPathResource、ServletContextResource、VfsResource等。

  • ByteArrayResource代表byte[]数组资源,getInputStream将返回一个ByteArrayInputStream。ByteArrayResource可多次读取数组资源,即isOpen ()永远返回false。
  • InputStreamResource代表java.io.InputStream字节流,对于“getInputStream ”操作将直接返回该字节流,因此只能读取一次该字节流,即“isOpen”永远返回true。
  • FileSystemResource代表java.io.File资源,对于“getInputStream ”操作将返回底层文件的字节流,“isOpen”将永远返回false,从而表示可多次读取底层文件的字节流。
  • ClassPathResource代表classpath路径的资源,将使用ClassLoader进行加载资源。classpath 资源存在于类路径中的文件系统中或jar包里,且“isOpen”永远返回false,表示可多次读取资源。
    ClassPathResource加载资源替代了Class类和ClassLoader类的“getResource(String name)”和“getResourceAsStream(String name)”两个加载类路径资源方法,提供一致的访问方式。

给出一个示例,集中实现都差不多

@Test    public void testByteArrayResource() {        Resource resource = new ByteArrayResource("Hello world".getBytes());        if (resource.exists()) {            InputStream is = null;            try {                // 打开资源                is = resource.getInputStream();                // 读取资源                byte data[] = new byte[1024];                int lenth = 0;                while ((lenth = is.read(data)) != -1) {                    System.out.println(new String(data));                }            } catch (IOException e) {                e.printStackTrace();            } finally {                if (is != null) {                    try {                        is.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }    }
0 0
原创粉丝点击