FileInputStream vs ClassPathResource vs getResourceAsStream and file integrity

I have a strange problem:

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

If I do this:

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

Or that:

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

Or that:

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

When I try to create a book:

 Workbook wb = new XSSFWorkbook(is); 

I get this error:

 java.util.zip.ZipException: invalid block type 

BUT, when I get my file as follows:

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

It works!

What's wrong? I can not hardcode the full path to the file.

Can someone help me?

thanks

+8
java stream apache-poi
source share
2 answers

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

This code loads a file from source, unfiltered

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

This code loads the file from the destination directory after maven has filtered the contents

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

You should not filter binaries such as excel and use two mutually exclusive sets of resources, as described at the bottom of this page the maven resource plugin

+18
source share

You are not trying to access it, for example

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

?

0
source share

All Articles