spring 之 FileSystemResource

1、来源

FileSystemResource 是 Spring 框架中 Resource 接口的一个实现类,主要用于访问文件系统中的资源。这个类封装了对文件系统的直接访问能力,使得在 Spring 的上下文中可以方便地以统一的方式处理本地文件。

2、作用

1)统一资源访问接口

Spring 提供了 Resource 接口来抽象不同类型的资源(如文件、类路径资源、URL 资源等),而 FileSystemResource 是针对文件系统资源的实现,提供了一种与具体文件系统交互的标准方式。

2)读取和操作文件

通过 FileSystemResource,开发者能够根据给定的文件系统路径读取文件内容、获取文件信息(如文件名、路径、是否存在、最后修改时间等)以及进行文件的读写操作。

3)集成到 Spring 框架中

在 Spring 的配置文件加载、组件扫描、自动装配等场景下,当需要从文件系统加载资源时,会隐式或显式地创建 FileSystemResource 对象

3、案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.core.io.FileSystemResource;

// 创建一个指向文件系统的资源对象
FileSystemResource resource = new FileSystemResource("/path/to/myfile.txt");

// 使用资源对象读取文件内容
InputStream inputStream = resource.getInputStream();
byte[] contentBytes = StreamUtils.copyToByteArray(inputStream);

// 或者使用Spring的Resource工具方法直接读取字符串内容
String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));

// 获取文件相关信息
boolean exists = resource.exists();
long lastModified = resource.lastModified();

// 写入文件
OutputStream outputStream = resource.getOutputStream();
outputStream.write(someData);
outputStream.close();