通过apache poi读取excel文件(在classpath中)

我想阅读(使用Apache poi).xlsx文件,这是不是在文件系统,但在类path。 我正在使用maven – 所以它在资源文件夹。

我的代码是 –

InputStream resourceAsStream = MyReader.class.getClassLoader().getResourceAsStream("test.xlsx"); Workbook wb = new XSSFWorkbook(resourceAsStream); 

我得到这个例外。

 Caused by: java.lang.IllegalArgumentException: MALFORMED at java.util.zip.ZipCoder.toString(ZipCoder.java:58) ~[?:1.7.0_51] at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:297) ~[?:1.7.0_51] at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:121) ~[?:1.7.0_51] at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:51) ~[poi a3] at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:88) ~[poi-ooxml-3.11-beta3.jar:3.11-beta3] at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:272) ~[poi-ooxml-3.11-beta3.jar:3.11-beta3] at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37) ~[poi-ooxml-3.11-beta3.jar:3.11-beta3] 

当我从文件系统读取相同的文件时,一切都很好。 我的代码中是否有错误,或者我想知道什么?

UPDATE1:这是在web应用程序,所以代码部署在tomcat 7。

更新2:当我用这种方式读取相同的文件 – 它的工作原理。

 File file = new File("C:\\Users\\.....\\test.xlsx"); FileInputStream fileInputStream = new FileInputStream(file); Workbook wb = new XSSFWorkbook(fileInputStream); 

谢谢

花了几天,在这个问题上,我发现了一个答案在stackoverflow))。 FileInputStream vs ClassPathResource vs getResourceAsStream和文件的完整性

在Maven资源插件过滤中的问题,它破坏了Excel文件。

 You should not filter binary files like excel and use two mutually exclusive resource sets as described at the bottom of this page 

maven资源插件

该文件位于类path的顶部,即在WEB-INF / classes中?

Classloader.getResource()的API文档说资源名称是:

“资源的名称是一个'/'分隔的path名称,标识资源。”

因此,如果您的文件位于某个子目录中,则该path应该是资源名称的一部分。

添加更多的信息到@ user1321466答案,过滤你可以做到maven资源插件网站所描述的:

如果你有两个文本文件和二进制文件作为资源,build议有两个分开的文件夹。 一个文件夹src / main / resources(缺省值)用于未筛选的资源,另一个文件夹src / main / resources-filtered用于筛选的资源。

或者只是从过滤中排除文件:

 <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <excludes> <exclude>**/*.xsd</exclude> <exclude>**/*.xml</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <includes> <include>**/*.xsl</include> <include>**/*.xslx</include> </includes> </resource>