spring学习笔记 -- 资源访问(Resource接口)
概述:
package com.cxyapi.spring.resource;import java.io.File;import org.apache.commons.io.IOUtils;import org.junit.Test;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;/** * @author cxy@cxyapi.com * spring学习笔记 - 资源访问(Resource接口) * 说明: * 主要介绍3种方式(当然不止三种,但是这三种基本能应付大多需求) * FileSystemResource:以文件的绝对路径方式进行访问 * ClassPathResource:以类路径的方式访问 * ServletContextResource:web应用根目录的方式访问 */public class ResourceTest{/** * FileSystemResource * 文件系统资源访问:以文件系统的绝对路径方式进行访问 */@Testpublic void FileSystemResourceTest() throws Exception{String filePath="D:/cxyapi/show.txt";FileSystemResource res1=new FileSystemResource(filePath);if(res1.exists()){System.out.println("资源的文件名:"+res1.getFilename());System.out.println("资源的文件大小:"+res1.contentLength());//可以获取输入流和输出流,然后配合apache common的IOUtils 读取内容System.out.println("文件内容:"+IOUtils.toString(res1.getInputStream(),"GB2312"));File f=res1.getFile();//转换成Java的File对象}else{System.out.println("指定资源不存在");}}/** * ClassPathResource:以类路径的方式访问 */@Testpublic void ClassPathResourceTest() throws Exception{Resource res=new ClassPathResource("aop.xml");//对应的文件路径:E:\workspace\SpringTest\WebContent\WEB-INF\classes\aop.xmlSystem.out.println("文件的物理路径:"+res.getFile().getAbsolutePath());System.out.println("对应的以往的实现方式:"+this.getClass().getResource("/").getPath());}}?
? ?ServletContextResource的测试写在了jsp中,因为这个方法需要jsp内置对象application作为参数
<%@page import="org.springframework.core.io.support.EncodedResource"%><%@page import="org.springframework.util.FileCopyUtils"%><%@page import="org.springframework.web.context.support.ServletContextResource"%><%@page import="org.springframework.core.io.Resource"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>ServletContextResource测试</title></head><body><%//文件的相对路径是Web应用的根路径 也就是 WebContent 或者是 WebRoot(超级实用)Resource res = new ServletContextResource(application,"/configTest/cxyapi.txt");String fileName=res.getFilename();//做个转码 输出文件内容EncodedResource encRes=new EncodedResource(res,"UTF-8");String fileContent=FileCopyUtils.copyToString(encRes.getReader()).replaceAll("\r\n", "<br/>");%><p><b>文件名称:</b><%=fileName%></p><p><b>文件内容:</b><br/><%=fileContent%></p></body></html>?
?
声明:
1.原创文章,转载请标明并加本文连接。
2.文章反映个人愚见,如有异议欢迎讨论指正
3.更多的内容请看我的 ?个人博客(测试版)