简体   繁体   English

FileInputStream vs ClassPathResource vs getResourceAsStream和文件完整性

[英]FileInputStream vs ClassPathResource vs getResourceAsStream and file integrity

I have a weird problem : 我有一个奇怪的问题:

in src/main/resources i have a "template.xlsx" file. 在src / main / resources中我有一个“template.xlsx”文件。

If i do this : 如果我这样做:

InputStream is = new ClassPathResource("template.xlsx").getInputStream();

Or this : 或这个 :

InputStream is = ClassLoader.getSystemResourceAsStream("template.xlsx");

Or this : 或这个 :

InputStream is = getClass().getResourceAsStream("/template.xlsx");

When i try to create a workbook : 当我尝试创建工作簿时:

Workbook wb = new XSSFWorkbook(is);

I get this error : 我收到此错误:

java.util.zip.ZipException: invalid block type

BUT, when i get my file like this : 但是,当我得到这样的文件时:

InputStream is = new FileInputStream("C:/.../src/main/resources/template.xlsx");

It works ! 有用 !

What is wrong ? 怎么了 ? I can't hardcode the fullpath to the file. 我无法将完整路径硬编码到文件中。

Can someone help me with this ? 有人可以帮我弄这个吗 ?

Thanks 谢谢

I had the same issue, you probably have a problem with maven filtering. 我有同样的问题,你可能有maven过滤问题。

This code load the file from source, unfiltered 此代码从源代码加载文件,未经过滤

InputStream is = new FileInputStream("C:/.../src/main/resources/template.xlsx");

This code load the file from the target directory, after maven has filtered the content 在maven过滤内容后,此代码从目标目录加载文件

InputStream is = getClass().getResourceAsStream("/template.xlsx");

You should not filter binary files like excel and use two mutually exclusive resource sets as described at the bottom of this page maven resources plugin 您不应过滤像excel这样的二进制文件,并使用两个互斥的资源集,如本页底部maven resources插件所述

haven't you try accessing it like 你有没有试过像它一样访问它

InputStream is = new FileInputStream("/main/resources/template.xlsx");

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM