Java-利用Spring提供的Resource/ResourceLoader接口操作资源文件

简介: Java-利用Spring提供的Resource/ResourceLoader接口操作资源文件

背景


JDK提供的访问资源的类(如java.net.URL、File等)并不能很好地满足各种底层资源的访问需求,比如缺少从类路径或者Web容器上下文中获取资源的操作类。

Spring提供了Resource接口,为应用提供了更强的底层资源访问能力,该接口拥有对应不同资源类型的实现类。


资源访问接口

主要方法

20170708100333662.jpgboolean exists() 资源是否存在

boolean isOpen() 资源是否打开

URL getURL() throws IOException 如果底层资源可以表示成URL,则该方法放回对应的URL对象

File getFile() throws IOException 如果底层资源对应一个文件,这返回对应的File对象

Spring框架使用Resource装载各种资源,包括配置文件资源、国际化属性文件资源等。


主要实现类

20170708103443809.jpg


WritableResource : 可写资源接口,Spring3.1新增的接口,有2个实现类: FileSystemResource和PathResource。 其中PathResource是Spring4.0提供的实现类

ByteArrayResource:二进制数组表示的资源,二进制数组资源可以在内存中通过程序构造。

ClassPathResource:类路径下的资源,资源以相对于类路径的方式表示,一般是以相对于根路径的方式

FileSystemResouce:文件系统资源,资源以文件系统路径的方式表示

InputStreamResource:以输入流返回标识的资源

ServletContextResource:为访问Web容器上下文中的资源而设计的类,负责以相对于Web应用根目录的路径来加载资源。支持以流和URL的访问能行事,在war包解包的情况下,也可以通过File方式访问。 该类还可以直接从JAR包中访问资源。

UrlResource:封装了java.net.URL,它使用户能够访问任何可以通过URL表示的资源,如文件系统的资源,HTTP资源,FTP资源

PathResource : Spring4.0提供的读取资源文件的新类。Ptah封装了java.net.URL、java.nio.file.Path(Java 7.0提供)、文件系统资源,它四用户能够访问任何可以通过URL、Path、系统文件路径标识的资源,如文件系统的资源,HTTP资源,FTP资源

有了这个抽象的资源类后,就可以将Spring配置文件放在任何地方(如数据库、LDAP中),只要最终通过Resource接口返回配置信息即可。


Spring的Resource接口及其实现类可以在脱离Spring框架的情况下适用,比JDK更方便更强大.


例子


假设一个Web应用下有一个文件,用户可以通过以下几种方式对这个资源文件进行访问:

  1. 通过FileSystemResource以文件绝对路径的方式进行访问
  2. 通过ClassPathResource以类路径的方式进行访问
  3. 通过ServletContextResource以相对Web应用根目录的方式进行访问


WritableResource / ClassPathResource


20170708113748065.jpg

package com.xgj.service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.WritableResource;
/**
 * 
 * @ClassName: ResourceLoadTest
 * @Description: 跟这个模块无关,仅仅是为了测试 Resource接口操作文件
 * @author: Mr.Yang
 * @date: 2017年7月7日 下午11:38:19
 */
public class ResourceLoadTest {
    public static void main(String[] args) {
        try {
            String filePath = "D:/workspace/workspace-jee/HelloSpring/hello-spring4/src/test/resources/resourcefiletest.txt";
            // (1)使用系统文件路径加载文件
            WritableResource res = new FileSystemResource(filePath);
            // PathResource  @since 4.0
            //WritableResource res = new PathResource(filePath);
            System.out.println(res.getFilename());
            // (2)使用类路径方式加载spring-context.xml文件
            ClassPathResource classPathResource = new ClassPathResource("spring-context.xml");
            System.out.println(classPathResource.getFilename());
            // (3)使用WritableResource接口写资源文件
            OutputStream os = res.getOutputStream();
            os.write("小工匠的使用Resource接口测试".getBytes());
            os.close();
            // (4)使用Resource接口读取资源文件
            InputStream ins = res.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int i;
            while ((i = ins.read()) != -1) {
                bos.write(i);
            }
            System.out.println("读取的文件:" + res.getFilename() + ",内容:" + bos.toString());
            // 读取spring-context.xml的内容
            InputStream ins2 = classPathResource.getInputStream();
            int j;
            while ((j = ins2.read()) != -1) {
                bos.write(j);
            }
            //System.out.println("读取的文件:" + classPathResource.getFilename() + ",内容:" + bos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


输出:

resourcefiletest.txt
spring-context.xml
读取的文件:resourcefiletest.txt,内容:小工匠的使用Resource接口测试


ServletContextResource

20170708120652238.jpg

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<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" />
<!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=ISO-8859-1">
<title>ResourceTest,nothing to do with this module</title>
</head>
<body>
    <%
        Resource res3 = new ServletContextResource(application, "/WEB-INF/classes/spring-context.xml");
        out.print(res3.getFilename() + "<br/>");
        out.print(WebUtils.getTempDir(application).getAbsolutePath());
    %>
</body>
</html>


运行:


20170708120740259.jpg

对资源文件编码

// (2)使用类路径方式加载spring-context.xml文件
ClassPathResource classPathResource = new ClassPathResource("spring-context.xml");
System.out.println(classPathResource.getFilename());
// 以UTF-8编码
EncodedResource ens = new EncodedResource(classPathResource ,"UTF-8");
String content = FileCopyUtils.copyToString(ens.getReader());
System.out.println("编码后的内容:\n" +content);


资源加载


通过上面的例子,是不是发现 ,为了访问不同类型的资源,必须使用相应的Resource实现类。


是否可以在不显式使用Resource实现类的情况下,仅仅通过资源地址的特殊标示符就可以访问相应的资源? 答案是肯定的,Spring提供了一个强大的加载资源的方式,不仅能通过“classpath:”、“file:”等资源地址前缀识别不同的资源类型,还支持Ant风格带通配符的资源地址。


资源地址表达式

Spring支持的资源类型的地址前缀


image.png


注意事项 classpath: 和 classpath*:

举个例子: 假设有多个Jar包或者文件系统类路径下拥有一个相同包名(com.xgj)


classpath: 只会加载第一个加载的com.xgj包的类路径下查找

classpath*: 会扫描到所有的这些jar包及类路径下出下的com.xgj类路径。


使用场景:


一般情况下,我们的应用都是有各个模块组成的,对于分模块打包的应用,假设我们有一个应用,分为N个模块,一个模块对应一个配置文件,分别为module1.xml 、module2xml、module3.xml….等,都放在了com.xgj的目录下,每个模块单独打成jar包。


我们可以使用 classpath*:com/xgj/module*.xml加载所有模块的配置文件。


如果使用classpath:com/xgj/module*.xml 只会加载一个模块的配置文件


Ant风格的资源地址

Ant风格的资源地址支持三种匹配符

  • ? 匹配文件名中的一个字符
  • * 匹配文件名中的任意字符
  • ** 匹配多层路径


示例:

classpath:com/t?st.xml


匹配com类路径下的 com/test.xml com/tast.xml等


file:D:/conf/*.xml

匹配文件系统D:/conf/目录下所有以.xml为后缀的文件


classpath:com/**/test.xml


匹配com类路径下(当前目录及子孙目录)的test.xml


classpath:org/springframework/**/*.xml


匹配类路径org/springframework/下是有的以.xml为后缀的文件


classpath:org/**/servlet/bla.xml


匹配类路径org任意层级的 /servlet/bla.xml的文件


资源加载器

介绍

Spring定义了一套资源加载的接口,并提供了实现类


20170710060722315.jpg

其中


20170710060928475.jpg


ResourceLoader中的方法Resource getResource(String location);

可以根据一个资源地址加载文件资源, 不过ResourceLoader这个接口方法中的资源地址仅支持带资源类型前缀的表达式,不支持Ant风格的资源路径表达式。


不过 ResourcePatternResolver 扩展了 ResourceLoader接口,


20170710061234419.jpg

ResourcePatternResolver 的getResource方法支持带资源类型前缀以及Ant风格的资源路径表达式。

PathMatchingResourcePatternResolver 是Spring提供的标准实现类。

20170710061508609.jpg


示例

package com.xgj.service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
 * 
 * 
 * @ClassName: ResourceLoaderTest
 * 
 * @Description: 跟这个模块无关,仅仅是为了测试 ResourceLoa接口操作文件
 * 
 * @author: Mr.Yang
 * 
 * @date: 2017年7月9日 下午7:51:37
 */
public abstract class ResourceLoaderTest {
    static Logger logger = Logger.getLogger(ResourceLoaderTest.class);
    static ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    public static void main(String[] args) {
        try {
            readFromClasspath();
            readFromHttp();
            readFromFile();
            readFromFTP();
            readFromNoPreFix();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 
     * 
     * @Title: readFromClasspath
     * 
     * @Description: 读取 classpath: 地址前缀的文件
     * 
     * @throws IOException
     * 
     * @return: void
     */
    public static void readFromClasspath() throws IOException {
        Resource[] resources = resourcePatternResolver.getResources("classpath*:com/xgj/conf/**/*.xml");
        for (Resource resource : resources) {
            System.out.println(resource.getDescription());
            readContent(resource);
        }
    }
    public static void readFromNoPreFix() throws IOException {
        Resource resource = resourcePatternResolver.getResource("spring-context.xml");
        System.out.println(resource.getDescription());
        readContent(resource);
    }
    /**
     * 
     * 
     * @Title: readFromFile
     * 
     * @Description: 使用UrlResource从文件系统目录中装载资源,可以采用绝对路径或者相对路径
     * 
     * @throws IOException
     * 
     * @return: void
     */
    public static void readFromFile() throws IOException {
        Resource resource = resourcePatternResolver.getResource(
                "file:/D:/workspace/workspace-jee/HelloSpring/hello-spring4/src/main/java/com/xgj/conf/conf2/test2.xml");
        readContent(resource);
    }
    /**
     * 
     * 
     * @Title: readFromHttp
     * 
     * @Description: 使用UrlResource从web服务器中加载资源
     * 
     * @throws IOException
     * 
     * @return: void
     */
    public static void readFromHttp() throws IOException {
        Resource resource = resourcePatternResolver.getResource("http://127.0.0.1:8080/hello-spring4/index.jsp");
        System.out.println(resource.getDescription());
        readContent(resource);
    }
    /**
     * 
     * 
     * @Title: readFromFTP
     * 
     * @Description: 这里只演示写法,因为这个服务器要求用户名和密码,其实是无法读取的。
     * 
     * @throws IOException
     * 
     * @return: void
     */
    public static void readFromFTP() throws IOException {
        Resource resource = resourcePatternResolver
                .getResource("ftp://172.25.243.81/webserver/config/logback.xml");
    }
    /**
     * 
     * 
     * @Title: readContent
     * 
     * @Description: 读取获取到的资源文件的内容
     * 
     * @param resource
     * @throws IOException
     * 
     * @return: void
     */
    public static void readContent(Resource resource) throws IOException {
        InputStream ins = resource.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int i;
        while ((i = ins.read()) != -1) {
            bos.write(i);
        }
        logger.debug("读取的文件:" + resource.getFilename() + ",/n内容:/n" + bos.toString());
    }
}


注意事项


使用Resource操作文件时,如果资源的配置文件在项目发布的时候会打包到jar中,那么就不能使用Resource.getFile()方法,否则会抛出FileNotFoundException异常。


推荐使用 Resource.getInputStream()读取。

错误的方式

(new DefaultResourceLoader()).getResource("classpath:conf/sys.properties").getFile();


正确的方式

(new DefaultResourceLoader()).getResource("classpath:conf/sys.properties").getInputStream();


建议尽量使用流的方式读取,避免环境不同造成问题

相关文章
|
7天前
|
缓存 Java 应用服务中间件
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
java语言后台管理若依框架-登录提示404-接口异常-系统接口404异常如何处理-登录验证码不显示prod-api/captchaImage 404 (Not Found) 如何处理-解决方案优雅草卓伊凡
35 5
|
8天前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
39 7
|
18天前
|
存储 NoSQL Java
使用Java和Spring Data构建数据访问层
本文介绍了如何使用 Java 和 Spring Data 构建数据访问层的完整过程。通过创建实体类、存储库接口、服务类和控制器类,实现了对数据库的基本操作。这种方法不仅简化了数据访问层的开发,还提高了代码的可维护性和可读性。通过合理使用 Spring Data 提供的功能,可以大幅提升开发效率。
60 21
|
1月前
|
监控 JavaScript 数据可视化
建筑施工一体化信息管理平台源码,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
智慧工地云平台是专为建筑施工领域打造的一体化信息管理平台,利用大数据、云计算、物联网等技术,实现施工区域各系统数据汇总与可视化管理。平台涵盖人员、设备、物料、环境等关键因素的实时监控与数据分析,提供远程指挥、决策支持等功能,提升工作效率,促进产业信息化发展。系统由PC端、APP移动端及项目、监管、数据屏三大平台组成,支持微服务架构,采用Java、Spring Cloud、Vue等技术开发。
|
1月前
|
Java Spring
Java Spring Boot监听事件和处理事件
通过上述步骤,我们可以在Java Spring Boot应用中实现事件的发布和监听。事件驱动模型可以帮助我们实现组件间的松耦合,提升系统的可维护性和可扩展性。无论是处理业务逻辑还是系统事件,Spring Boot的事件机制都提供了强大的支持和灵活性。希望本文能为您的开发工作提供实用的指导和帮助。
103 15
|
2月前
|
数据采集 JSON Java
利用Java获取京东SKU接口指南
本文介绍如何使用Java通过京东API获取商品SKU信息。首先,需注册京东开放平台账号并创建应用以获取AppKey和AppSecret。接着,查阅API文档了解调用方法。明确商品ID后,构建请求参数并通过HTTP客户端发送请求。最后,解析返回的JSON数据提取SKU信息。注意遵守API调用频率限制及数据保护法规。此方法适用于电商平台及其他数据获取场景。
|
2月前
|
安全 Java API
java如何请求接口然后终止某个线程
通过本文的介绍,您应该能够理解如何在Java中请求接口并根据返回结果终止某个线程。合理使用标志位或 `interrupt`方法可以确保线程的安全终止,而处理好网络请求中的各种异常情况,可以提高程序的稳定性和可靠性。
60 6
|
2月前
|
Java 开发者 微服务
Spring Boot 入门:简化 Java Web 开发的强大工具
Spring Boot 是一个开源的 Java 基础框架,用于创建独立、生产级别的基于Spring框架的应用程序。它旨在简化Spring应用的初始搭建以及开发过程。
103 6
Spring Boot 入门:简化 Java Web 开发的强大工具
|
3月前
|
Java API
Java中内置的函数式接口
Java中内置的函数式接口
48 2
|
3月前
|
Java
在Java中,接口之间可以继承吗?
接口继承是一种重要的机制,它允许一个接口从另一个或多个接口继承方法和常量。
287 60

热门文章

最新文章