Spring的资源访问

一、概述
spring改进了java资源访问的策略,Spring为资源访问提供了一个Resource接口,该接口提供了更强的资源访问能力。
Resource接口中主要定义有以下方法:
1、 exists():用于判断对应的资源是否真的存在。
2、sReadable():用于判断对应资源的内容是否可读。需要注意的是当其结果为true的时候,其内容未必真的可读,但如果返回false,则其内容必定不可读。
3、 isOpen():用于判断当前资源是否代表一个已打开的输入流,如果结果为true,则表示当前资源的输入流不可多次读取,而且在读取以后需要对它进行关闭,以防止内存泄露。该方法主要针对于InputStreamResource,实现类中只有它的返回结果为true,其他都为false。
l4、 getURL():返回当前资源对应的URL。如果当前资源不能解析为一个URL则会抛出异常。如ByteArrayResource就不能解析为一个URL。
5、 getFile():返回当前资源对应的File。如果当前资源不能以绝对路径解析为一个File则会抛出异常。如ByteArrayResource就不能解析为一个File。
6、 getInputStream():获取当前资源代表的输入流。除了InputStreamResource以外,其它Resource实现类每次调用getInputStream()方法都将返回一个全新的InputStream。

二、Resource的实现类
1、ClassPathResource可用来获取类路径下的资源文件。对于web应用,ClassPathResource可自动搜索位于
WEB-INF/classes下的资源文件,无需使用绝对路径访问

package spring;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
/**
 * 访问加载路径下的资源
 * ClassPathResource可自动搜索位于WEB-INF/classes下的资源文件
 *
 */
public class ClassPathResourceTest {
    public static void main(String[] args) {
        ClassPathResource cpr=new ClassPathResource("book.xml");
       //获取资源的简单信息
        System.out.println(cpr.getFilename()+"========"+cpr.getDescription());
        //创建基于Dom4j的解析器
        SAXReader reader=new SAXReader();
        try {
            Document doc= reader.read(cpr.getFile());
            Element element=doc.getRootElement();
            List listElement=element.elements();
            Iterator<Element> it=listElement.iterator();
            //遍历根元素的全部子元素
            while(it.hasNext()){
                Element el=it.next();
                List elList=el.elements();
                Iterator<Element> its=elList.iterator();
                while(its.hasNext()){
                    Element element2=its.next();
                    System.out.println(element2.getText());
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
输出:
book.xml========class path resource [book.xml]
java
javaEE
C
C++

2、 UrlResource可用来代表URL对应的资源,它对URL做了一个简单的封装。通过给定一个URL地址,我们就能构建一个UrlResource。URL资源通常应该提供标准的协议前缀
file:用于访问文件系统
http:用于访问基于HTTP协议的网络资源
ftp:用于访问基于FTP协议的网络资源

package spring;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.UrlResource;
/**
 * 访问网络资源
 *
 */
public class UrlResourceTest {
    public static void main(String[] args) {
        try {
            //创建一个Resource对象,指定从文件系统里读取资源
            UrlResource url=new UrlResource("file:D:/workspaces/onlineShop/WebRoot/WEB-INF/classes/applicationContext.xml");
            //获取该资源的简单信息
            System.out.println(url.getFilename()+"---------"+url.getDescription());
            //创建基于Dom4j的解析器
            SAXReader reader=new SAXReader();
            try {
                Document document= reader.read(url.getFile());
                Element element= document.getRootElement();
                List list=element.elements();
                Iterator<Element> it=list.iterator();
                while (it.hasNext()) {
                    List list2=it.next().elements();
                    Iterator<Element> it2=list2.iterator();
                    while (it2.hasNext()) {
                        Element element2=it2.next();
                        System.out.println(element2.getName());

                    }
                }
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

3、 ByteArrayResource是针对于字节数组封装的资源,它的构建需要一个字节数组。

package spring;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ByteArrayResource;
/**
 * 访问字节数组资源
 * 
 */
public class ByteArrayResourceTest {
    public static void main(String[] args) {
        String file="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" 
                   +"<books>" 
                   +"<book name=\"Chinese\"><name>java</name><type>javaEE</type></book>" 
                   + "<book name=\"English\"><name>C</name><type>C++</type> </book>"
                   +"</books>";
        byte[]fileBytes=file.getBytes();
        ByteArrayResource bar=new ByteArrayResource(fileBytes);
        System.out.println(bar.getDescription());
        SAXReader reader=new SAXReader();
        try {
            Document doc= reader.read(bar.getInputStream());
            Element element=doc.getRootElement();
            List listElement=element.elements();
            Iterator<Element> it=listElement.iterator();
            while(it.hasNext()){
                Element el=it.next();
                List elList=el.elements();
                Iterator<Element> its=elList.iterator();
                while(its.hasNext()){
                    Element element2=its.next();
                    System.out.println(element2.getText());
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

4、ServletContextResource是针对于ServletContext封装的资源,用于访问ServletContext环境下的资源。ServletContextResource持有一个ServletContext的引用,其底层是通过ServletContext的getResource()方法和getResourceAsStream()方法来获取资源的。

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="org.springframework.web.context.support.ServletContextResource"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="org.dom4j.*" %>
<%@page import="java.io.*" %>
<%@page import="org.dom4j.io.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
ServletContextResource src=new ServletContextResource(application,"WEB-INF/book.xml");  
        out.print(src.getFilename()+"========"+src.getDescription());
        SAXReader reader=new SAXReader();
        try {
            Document doc= reader.read(src.getFile());
            Element element=doc.getRootElement();
            List listElement=element.elements();
            Iterator<Element> it=listElement.iterator();
            while(it.hasNext()){
                Element el=it.next();
                List elList=el.elements();
                Iterator<Element> its=elList.iterator();
                while(its.hasNext()){
                    Element element2=its.next();
                    out.println(element2.getText());
                }
            }
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title></title>
  </head>
  <body>
  </body>
</html>
发布了91 篇原创文章 · 获赞 7 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章