Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream vs ClassPathResource vs getResourceAsStream and file integrity

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

like image 368
Maxime ARNSTAMM Avatar asked Mar 23 '12 14:03

Maxime ARNSTAMM


1 Answers

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

like image 109
Thomas Vérin Avatar answered Sep 23 '22 15:09

Thomas Vérin