时间:2025-06-18 11:29
人气:
作者:admin
在开发时候遇到需要通过 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>
<!-- 方案一 -->
<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>
// 方案一
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();
本文来自博客园,作者:一块白板,转载请注明原文链接:https://www.cnblogs.com/ykbb/p/18934475/springboot-reads-files-under-resources-z1pwyth
上一篇:疯了!Java 被挤出前三。。