Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...