资源访问利器
2016-03-18 16:40
295 查看
Spring设计一个Resource接口,它为应用提供了更强的访问底层资源的能力。该接口拥有对应不同的资源类型的实现类。
1)boolean exists():资源是否存在;
2)boolean isOpen():资源是否打开;
3)URL getURL() throws IOException:如果底层资源可以表示成URL,该方法返回对应的URL对象;
4)File getFile() throws IOException:如果底层资源对应一个文件,该方法返回对应的File对象;
5)InputStream getInputStream() throws IOException:返回资源对应的输入流。
样例项目结构图:
FileSourceExample:
输出结果:
Haha
you get me!!!
hello
My name is LiuShiZhen~~
res1:file1.txt
res2:file1.txt
idnex.jsp:
输出结果:
1)boolean exists():资源是否存在;
2)boolean isOpen():资源是否打开;
3)URL getURL() throws IOException:如果底层资源可以表示成URL,该方法返回对应的URL对象;
4)File getFile() throws IOException:如果底层资源对应一个文件,该方法返回对应的File对象;
5)InputStream getInputStream() throws IOException:返回资源对应的输入流。
样例项目结构图:
FileSourceExample:
package com.resource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStream; /** * Created by gao on 16-3-18. */ public class FileSourceExample { public static void main(String[] args) { try { String filePath = "C:\\workspace\\Projects\\chapter03\\web\\WEB-INF\\classes\\conf\\file1.txt"; //使用系统文件路径方式加载文件 Resource res1 = new FileSystemResource(filePath); //使用类路径方式加载文件 Resource res2 = new ClassPathResource("file1.txt"); EncodedResource encRes = new EncodedResource(res2, "UTF-8"); String content = FileCopyUtils.copyToString(encRes.getReader()); System.out.println(content); InputStream ins1 = res1.getInputStream(); InputStream ins2 = res2.getInputStream(); System.out.println("res1:" + res1.getFilename()); System.out.println("res2:" + res2.getFilename()); } catch (IOException e) { e.printStackTrace(); } } }
输出结果:
Haha
you get me!!!
hello
My name is LiuShiZhen~~
res1:file1.txt
res2:file1.txt
idnex.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <jsp:directive.page import="org.springframework.web.context.support.ServletContextResource"/> <jsp:directive.page import="org.springframework.core.io.Resource"/> <jsp:directive.page import="org.springframework.web.util.WebUtils"/> <% Resource res3 = new ServletContextResource(application,"\\WEB-INF\\classes\\conf\\file1.txt"); out.print(res3.getFilename()+"<br/>"); out.print(WebUtils.getTempDir(application).getAbsolutePath()); %>
输出结果:
相关文章推荐
- storm-0.8.2源码分析2之nimbus运行过程(一)
- 蓝桥杯之年月日得到周几(年月日问题,包含平瑞年算法)
- 【技术分享】【mysql】ubuntu14.04下 mysql5.6源码安装
- sql 联合查询
- python的版本切换
- AndroidStudio引入环信easeui库出错
- Hbase常用shell
- MFC常用控件(一)
- maven tomcat插件热部署配置过程
- 移动端浏览器有哪些,内核分别是什么
- 对于属性操作,加入属性,移除属性
- ecshop数据表说明
- spring 拦截器
- ubuntu软件源设置
- [快速傅里叶变换--FFT]
- storm-0.8.2源码分析2之topology启动
- 使用VS GDB扩充套件在VS上远端侦错Linux上的C/C++程序
- 我的Python成长之路---第六天---Python基础(20)---2016年2月20日(晴)
- Win10如何用文件检查器检查修复系统的受损文件?Win10修复受损文件的技巧
- 关于ajaxFileUpload上传文件时第二次上传无效的解决办法