前言
JDK提供的资源访问类,如java.net.URL,File等,在Spring中并不能满足我们的需求,比如,缺少从类路径或者Web容器的上下文中获取资源的操作类。
因此,Spring设计了Resource接口,为应用提供更强的底层资源访问能力,该接口拥有对应不同资源的实现类。
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:返回资源对应的输入流;
Resource及其实现类
Resource在Spring中起着举足轻重的作用,Spring框架使用它来装载各种资源,比如配置文件资源。Resource及其实现类关系如下图:
2.ByteArrayResource:二进制数组表示的资源;
3.InputStreamResource:以输入流表示返回的资源;
4.UrlResource:获得任何能以URL表示的资源,比如HTTP资源;
5.ClassPathResource:类路径下的资源,资源以相对于类路径的方式表示;
6.FileSystemResource:文件系统资源,资源以文件系统路径的方式表示;
7.ServletContextResource:访问Web容器的上下文资源,以相对于Web应用根目录的路径加载资源;
8.PathResource:Spring 4.0提供的API。能够获得任何可以通过URL,Path和文件系统路径表示的资源;
实战
有个文件位于Web应用的类路径下,我们可以通过以下几种方式进行访问。
1.FileSystemResource:以文件系统绝对路径的方式访问;
2.ClassPathResource:以类路径的方式访问;
3.ServletContextResource:以相对于Web应用根目录的方式访问;
try{
//文件路径名
String filePath="D:/User/Documents/IdeaProjects/readinglist/src/main/resources/test.txt";
//使用文件系统路径加载资源
WritableResource res1=new PathResource(filePath);
//使用类路径的方式访问
Resource res2=new ClassPathResource("test.txt");
//写入资源文件
OutputStream stream1 = res1.getOutputStream();
stream1.write("dfd".getBytes());
stream1.close();
//读资源文件
InputStream ins1=res1.getInputStream();
InputStream ins2=res2.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int i=1;
while ((i=ins1.read())!= -1){
baos.write(i);
}
System.out.println(baos.toString());
//获取文件名字
System.out.println(res1.getFilename());
System.out.println(res2.getFilename());
}catch (IOException e){
e.printStackTrace();
}