Spring 项目读取 resource 下的资源文件

   我们在项目中经常碰到需要读取固定文件的场景,如模板文件。一般做法是将文件放在 resources 目录下,程序通过多种方式可以顺利读取文件。在此记录一下,自己认为比较稳妥的读取方式及可能遇到的问题。

项目环境:Spring Boot 2.3


一、读取 resources 下的文件

  1. 将文件放置在 resources/file 目录下,读取文件流的示例代码如下:
1
2
3
4
// 读取测试文件 
Resource resource = new ClassPathResource("file/test.txt");
// 获取流
InputStream inputStream = resource.getInputStream();

二、可能的问题

  1. 如果要获取 File 对象,不能直接使用“resource.getFile()”获取;
  2. 因为在打包成 Jar 包后,使用 File 访问不到资源内容,运行会出现”java.io.FileNotFoundException”错误,只能通过流读取文件内容;

三、正确方式

  1. 如果需要获取 File 对象,只能通过写临时文件的方式进行,临时文件使用完毕后再删除;
  2. 示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 用到了 commons-io 包的 FileUtils 工具类 

// 读取文件
Resource resource = new ClassPathResource("file/test.txt");
// 获取系统临时目录
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
// 将文件写入临时目录
File tempFile = new File(tempDir + "/test.txt");
try (InputStream inputStream = resource.getInputStream();) {
FileUtils.copyInputStreamToFile(inputStream, tempFile);
}

// TODO 使用临时文件

// 删除临时文件
tempFile.delete();