SpringBoot读取Resources目录文件的办法探究
背景
在进行开发活动时,遇到了需要利用Resources目录下的某个excel文件作为模板来生成文件的情形。但在使用POI读取文件的时候,出现了No valid entries or contents found, this is not a valid 00xML (office open XML) fil.
的错误,该错误表明读取的文件格式有误。
通过对比从Resources下读取和从外部读取同一份文件的情况,发现两者的文件大小不相同,并且Resources下的文件已经损坏。造成此问题可能的情况是(当时忘记查看pom.xml,以下纯属猜测)
<build>
<resources>
<!-- 可能没设置该项 -->
<resource>
<directory>src/main/resources</directory>
<!-- 此项设置成如下 -->
<filtering>true</filtering>
</resource>
</resources>
</build>
目标
- 能够在运行的时候读取到Resources下的文件
- 消除POI读取时出现的错误
具体操作
修改pom.xml文件
<!-- 方案一 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
</build>
<!-- 方案二 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<!--不加这一行,xlsx文件会被过滤,然后在maven build的时候,去target下看对应的xlsx就是损坏的-->
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
读取Resources下的文件
// 方案一
File file = new File("D:\\1.xlsx");
InputStream resourceAsStream = ScheduleTask.class.getClassLoader().getResourceAsStream("1.xlsx");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(resourceAsStream.readAllBytes());
fileOutputStream.flush();
fileOutputStream.close();
resourceAsStream.close();
// 方案二
File file = ResourceUtils.getFile("classpath:1.xlsx");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\1.xlsx");
fileOutputStream.write(fileInputStream.readAllBytes());
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
总结
- POI读取出现错误主要是因为在构建的时候文件没有被正确写入,只需对pom.xml文件进行调整就能让POI正确读取文件。
- 在实践中发现采用pom.xml修改中的第一种方案时,似乎与nacos存在冲突,建议采用方案二。
相关文章
暂无评论...