FileInputStream vs ClassPathResource vs getResourc

2020-02-09 09:42发布

问题:

I have a weird problem :

in src/main/resources i have a "template.xlsx" file.

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

回答1:

I had the same issue, you probably have a problem with maven filtering.

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

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



回答2:

haven't you try accessing it like

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

?