您的位置:首页 > 其它

资源访问利器

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:

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());
%>


输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: