- 我们在项目中经常碰到需要读取固定文件的场景,如模板文件。一般做法是将文件放在resources目录下,程序通过多种方式可以顺利读取文件。在此记录一下,自己认为比较稳妥的读取方式及可能遇到的问题。
- 项目环境:Spring Boot 2.3
一、读取resources下的文件
- 将文件放置在resources/file目录下,读取文件流的示例代码如下:
Resource resource = new ClassPathResource("file/test.txt");
InputStream inputStream = resource.getInputStream();
二、可能的问题
- 如果要获取File对象,不能直接使用“resource.getFile()”获取;
- 因为在打包成Jar包后,使用File访问不到资源内容,运行会出现"java.io.FileNotFoundException"错误,只能通过流读取文件内容;
三、正确方式
- 如果需要获取File对象,只能通过写临时文件的方式进行,临时文件使用完毕后再删除;
- 示例代码如下:
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);
}
tempFile.delete();